Unverified Commit 957f5ed3 authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

[Backport] Fixes to support TypeScript 7 (#95831)

Backports the TypeScript 7 support fixes to the `16.2.x` release line to
resolve #95801, where `next build` crashes with a silent
`SIGSEGV`/`SIGABRT` when `typescript@7` is installed (the legacy
TypeScript JavaScript API is unavailable in TS7).

Cherry-picks the following, in order:

- #92277 — Resolve `compilerOptions.paths` in tsconfigs without
`compilerOptions.baseUrl` (prerequisite; source change only)
- #95639 — (TypeScript 7 Support) Add experimental TypeScript CLI
backend
- #95692 — Fix termination handling
- #95753 — Better support the CLI spinner when running the TSC CLI

Together these add the opt-in `experimental.useTypeScriptCli` backend
(runs the project-local `tsc` during `next build`, supporting TS7),
preserve the TypeScript API backend as the default with actionable TS7
migration guidance instead of a crash, and fix worker termination and
CLI spinner handling.

## Prerequisite: #92277

The TypeScript CLI backend tests exercise a `paths` alias that is
inherited from an extended tsconfig and defined **without** a `baseUrl`.
Resolving that alias in the **webpack** builder relies on the
`load-jsconfig.ts` change from #92277 (compute the effective base URL
from `pathsBasePath`), which had not been backported to `next-16-2`.
Only the source change from #92277 is included here — its test
reorganization is not.

## Test changes

The `test/production/ci-missing-typescript-deps` and
`test/production/next-server-nft` suites were converted from
`createNext` to `nextTestSetup` on `canary` in #93799, which was never
backported to `next-16-2`. Because #95639's test diffs were authored
against that refactored shape, the `ci-missing-typescript-deps` suite is
adapted back to this branch's existing `createNext` / `try‑finally`
style rather than pulling in the #93799 refactor.

## Fixes

Fixes #95801

## Verification

Automated (both bundlers):

- `pnpm --filter=next build`
- `pnpm test-start-turbo` and `pnpm test-start-webpack` for:
  - `test/production/app-dir/typescript-cli/typescript-cli.test.ts`
  - `test/production/ci-missing-typescript-deps/index.test.ts`
- Unit: `runTypeScriptCli.test.ts`,
`test/unit/typescript-cli-config-origin/index.test.ts`

Against a `typescript@7.0.2` reproduction project, `next build` no
longer crashes with an error about how `"id"` should be a string`. It
now exits cleanly with actionable guidance:

```
▲ Next.js 16.2.10 (Turbopack)

  Creating an optimized production build ...
✓ Compiled successfully in 785ms
  Running TypeScript  .TypeScript 7.0.2 does not provide the compiler API required by Next.js. Enable experimental.useTypeScriptCli in your Next.js config to use the TypeScript CLI, or install TypeScript 6 instead.
Next.js build worker exited with code: 1 and signal: null
```

The same clean error is produced under `CI=1` (previously the crash
path). Enabling the new opt-in:

```ts
experimental: {
  useTypeScriptCli: true,
},
```

makes the build succeed with TypeScript 7 installed.

---------
Co-authored-by: 's avatarTim Neutkens <tim@timneutkens.nl>
parent b56eb16e
---
title: useTypeScriptCli
description: Run the project-local TypeScript CLI for type checking during production builds.
version: experimental
---
The `experimental.useTypeScriptCli` option makes `next build` run the project-local `tsc` command instead of loading the TypeScript JavaScript compiler API. You can use this option with TypeScript 6, and it enables [TypeScript 7](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/) support while its JavaScript API is unavailable.
Install TypeScript 7 in your project:
```bash package="pnpm"
pnpm add -D typescript@^7
```
```bash package="npm"
npm install -D typescript@^7
```
```bash package="yarn"
yarn add -D typescript@^7
```
```bash package="bun"
bun add -D typescript@^7
```
Then, explicitly enable the CLI checker:
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
useTypeScriptCli: true,
},
}
export default nextConfig
```
```js filename="next.config.js" switcher
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
useTypeScriptCli: true,
},
}
module.exports = nextConfig
```
Next.js does not select the CLI checker automatically. If TypeScript 7 is installed without this option, `next build` exits with instructions to enable it or install a TypeScript version supported by the default checker.
## Behavior
- Next.js continues to generate `next-env.d.ts` and route types and to apply its recommended `tsconfig` settings before running the checker.
- TypeScript diagnostics are printed directly from `tsc`. Next.js-specific code frames and error rewriting are not applied.
- The complete project selected by the configured `tsconfig` file is checked, including test files and `.next/dev/types` when included. The [`--debug-build-paths`](/docs/app/api-reference/cli/next#next-build-options) option does not limit this set and produces a warning when combined with the CLI checker.
- [`typescript.tsconfigPath`](/docs/app/api-reference/config/typescript#custom-tsconfig-path) selects the project passed to `tsc`.
- [`typescript.ignoreBuildErrors`](/docs/app/api-reference/config/typescript#disabling-typescript-errors-in-production) skips the type-checking step, including the CLI checker.
Learn more about [using TypeScript 7 with Next.js](/docs/app/api-reference/config/typescript#using-typescript-7).
...@@ -11,6 +11,60 @@ To add TypeScript to an existing project, rename a file to `.ts` / `.tsx`. Run ` ...@@ -11,6 +11,60 @@ To add TypeScript to an existing project, rename a file to `.ts` / `.tsx`. Run `
> **Good to know**: If you already have a `jsconfig.json` file, copy the `paths` compiler option from the old `jsconfig.json` into the new `tsconfig.json` file, and delete the old `jsconfig.json` file. > **Good to know**: If you already have a `jsconfig.json` file, copy the `paths` compiler option from the old `jsconfig.json` into the new `tsconfig.json` file, and delete the old `jsconfig.json` file.
## Using TypeScript 7
[TypeScript 7](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/) does not currently provide the JavaScript compiler API that Next.js uses for type checking by default. To use TypeScript 7 during `next build`, install it in your project:
```bash package="pnpm"
pnpm add -D typescript@^7
```
```bash package="npm"
npm install -D typescript@^7
```
```bash package="yarn"
yarn add -D typescript@^7
```
```bash package="bun"
bun add -D typescript@^7
```
Then, opt in to running the project-local `tsc` CLI instead of the JavaScript API with [`experimental.useTypeScriptCli`](/docs/app/api-reference/config/next-config-js/useTypeScriptCli):
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
useTypeScriptCli: true,
},
}
export default nextConfig
```
```js filename="next.config.js" switcher
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
useTypeScriptCli: true,
},
}
module.exports = nextConfig
```
Next.js does not enable this option automatically. If you install TypeScript 7 without enabling `experimental.useTypeScriptCli`, `next build` exits with instructions to enable the option or install a TypeScript version supported by the default checker.
> **Good to know**:
>
> - CLI type checking prints the native `tsc` diagnostics. It does not apply Next.js-specific code frames or rewrite errors for routes, pages, layouts, or route handlers.
> - The CLI checks the complete project selected by your `tsconfig` file. This includes test files and `.next/dev/types` when they are included by that configuration. [`next build --debug-build-paths`](/docs/app/api-reference/cli/next#next-build-options) does not narrow the files that are type checked and produces a warning when used with this option.
> - [`typescript.tsconfigPath`](#custom-tsconfig-path) continues to select the configuration passed to `tsc`. [`typescript.ignoreBuildErrors`](#disabling-typescript-errors-in-production) skips the type-checking step, including the CLI checker.
> - `experimental.useTypeScriptCli` is experimental and its behavior may change.
<AppOnly> <AppOnly>
## IDE Plugin ## IDE Plugin
...@@ -31,7 +85,7 @@ You can enable the plugin in VS Code by: ...@@ -31,7 +85,7 @@ You can enable the plugin in VS Code by:
height="637" height="637"
/> />
Now, when editing files, the custom plugin will be enabled. When running `next build`, the custom type checker will be used. Now, when editing files, the custom plugin will be enabled. By default, the custom type checker is used when running `next build`. When [`experimental.useTypeScriptCli`](#using-typescript-7) is enabled, the project-local `tsc` CLI is used instead.
The TypeScript plugin can help with: The TypeScript plugin can help with:
......
---
title: useTypeScriptCli
description: Run the project-local TypeScript CLI for type checking during production builds.
source: app/api-reference/config/next-config-js/useTypeScriptCli
version: experimental
---
{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
...@@ -1146,5 +1146,8 @@ ...@@ -1146,5 +1146,8 @@
"1145": "Unsupported body type: %s", "1145": "Unsupported body type: %s",
"1146": "Invalid target hostname \"%s\" for proxy request, expected \"%s\"", "1146": "Invalid target hostname \"%s\" for proxy request, expected \"%s\"",
"1147": "Missing initURL", "1147": "Missing initURL",
"1148": "Could not determine origin for forwarded Server Actions request. This can happen if port or hostname are not configured for this server." "1148": "Could not determine origin for forwarded Server Actions request. This can happen if port or hostname are not configured for this server.",
"1149": "Could not parse output from TypeScript's --showConfig.",
"1150": "TypeScript %s does not provide the compiler API required by Next.js. Enable %s in your Next.js config to use the TypeScript CLI, or install TypeScript 6 instead.",
"1151": "TypeScript CLI interrupted by %s"
} }
...@@ -5,8 +5,14 @@ import * as Log from './output/log' ...@@ -5,8 +5,14 @@ import * as Log from './output/log'
import { getTypeScriptConfiguration } from '../lib/typescript/getTypeScriptConfiguration' import { getTypeScriptConfiguration } from '../lib/typescript/getTypeScriptConfiguration'
import { readFileSync } from 'fs' import { readFileSync } from 'fs'
import isError from '../lib/is-error' import isError from '../lib/is-error'
import { hasNecessaryDependencies } from '../lib/has-necessary-dependencies'
import { codeFrameColumns } from '../shared/lib/errors/code-frame' import { codeFrameColumns } from '../shared/lib/errors/code-frame'
import {
getTypeScriptApiMissingError,
getTypeScriptConfigurationCli,
getTypeScriptPackageInfo,
hasNativeTypeScriptPreview,
} from '../lib/typescript/runTypeScriptCli'
import { loadTsConfigOptions } from '../lib/typescript/loadTsConfig'
let TSCONFIG_WARNED = false let TSCONFIG_WARNED = false
...@@ -57,19 +63,24 @@ export default async function loadJsConfig( ...@@ -57,19 +63,24 @@ export default async function loadJsConfig(
jsConfigPath?: string jsConfigPath?: string
resolvedBaseUrl: ResolvedBaseUrl resolvedBaseUrl: ResolvedBaseUrl
}> { }> {
let typeScriptPath: string | undefined const useTypeScriptCli = Boolean(config.experimental.useTypeScriptCli)
try { const typeScriptPackage = getTypeScriptPackageInfo(dir)
const deps = hasNecessaryDependencies(dir, [ const typeScriptPath = useTypeScriptCli
{ ? typeScriptPackage?.tscPath
pkg: 'typescript', : typeScriptPackage?.apiPath
file: 'typescript/lib/typescript.js',
exportsRestrict: true,
},
])
typeScriptPath = deps.resolved.get('typescript')
} catch {}
const tsConfigFileName = config.typescript.tsconfigPath || 'tsconfig.json' const tsConfigFileName = config.typescript.tsconfigPath || 'tsconfig.json'
const tsConfigPath = path.join(dir, tsConfigFileName) const tsConfigPath = path.join(dir, tsConfigFileName)
if (
!useTypeScriptCli &&
typeScriptPackage &&
!typeScriptPackage.apiPath &&
!hasNativeTypeScriptPreview(dir) &&
fs.existsSync(tsConfigPath)
) {
throw getTypeScriptApiMissingError(typeScriptPackage.version)
}
const useTypeScript = Boolean(typeScriptPath && fs.existsSync(tsConfigPath)) const useTypeScript = Boolean(typeScriptPath && fs.existsSync(tsConfigPath))
let implicitBaseurl let implicitBaseurl
...@@ -81,11 +92,26 @@ export default async function loadJsConfig( ...@@ -81,11 +92,26 @@ export default async function loadJsConfig(
Log.info(`Using tsconfig file: ${tsConfigFileName}`) Log.info(`Using tsconfig file: ${tsConfigFileName}`)
} }
if (useTypeScriptCli) {
const tsConfig = await getTypeScriptConfigurationCli({
baseDir: dir,
tsConfigPath,
tscPath: typeScriptPath!,
})
const configOrigins = loadTsConfigOptions(tsConfigPath)
jsConfig = {
compilerOptions: {
...tsConfig.compilerOptions,
pathsBasePath: configOrigins.pathsBasePath,
},
}
} else {
const ts = (await Promise.resolve( const ts = (await Promise.resolve(
require(typeScriptPath!) require(typeScriptPath!)
)) as typeof import('typescript') )) as typeof import('typescript')
const tsConfig = await getTypeScriptConfiguration(ts, tsConfigPath, true) const tsConfig = await getTypeScriptConfiguration(ts, tsConfigPath, true)
jsConfig = { compilerOptions: tsConfig.options } jsConfig = { compilerOptions: tsConfig.options }
}
implicitBaseurl = path.dirname(tsConfigPath) implicitBaseurl = path.dirname(tsConfigPath)
} }
...@@ -98,13 +124,25 @@ export default async function loadJsConfig( ...@@ -98,13 +124,25 @@ export default async function loadJsConfig(
let resolvedBaseUrl: ResolvedBaseUrl let resolvedBaseUrl: ResolvedBaseUrl
if (jsConfig?.compilerOptions?.baseUrl) { if (jsConfig?.compilerOptions?.baseUrl) {
resolvedBaseUrl = { resolvedBaseUrl = {
baseUrl: path.resolve(dir, jsConfig.compilerOptions.baseUrl), baseUrl: path.resolve(
implicitBaseurl ?? dir,
jsConfig.compilerOptions.baseUrl
),
isImplicit: false, isImplicit: false,
} }
} else { } else {
if (implicitBaseurl) { // TypeScript 5.0+: `pathsBasePath` is the directory of the tsconfig that
// defines `paths`. For paths inherited from an extended base tsconfig (e.g.
// a workspace-root tsconfig.base.json for nx monorepo), this is the base
// config's directory — not the app tsconfig dir. Using it ensures JsConfigPathsPlugin
// joins path-mapping values against the correct base so `baseUrl` is not required
// for path aliases to work in webpack.
const pathsBasePath: string | undefined =
jsConfig?.compilerOptions?.pathsBasePath
const effectiveBaseUrl = pathsBasePath ?? implicitBaseurl
if (effectiveBaseUrl) {
resolvedBaseUrl = { resolvedBaseUrl = {
baseUrl: implicitBaseurl, baseUrl: effectiveBaseUrl,
isImplicit: true, isImplicit: true,
} }
} }
......
import type { Options as SWCOptions } from '@swc/core' import type { Options as SWCOptions } from '@swc/core'
import type { CompilerOptions } from 'typescript'
import path from 'node:path' import path from 'node:path'
import { readFileSync, existsSync } from 'node:fs' import { readFileSync, existsSync } from 'node:fs'
import { pathToFileURL } from 'node:url' import { pathToFileURL } from 'node:url'
import * as CommentJson from 'next/dist/compiled/comment-json'
import { deregisterHook, registerHook, requireFromString } from './require-hook' import { deregisterHook, registerHook, requireFromString } from './require-hook'
import { warn, warnOnce } from '../output/log' import { warn, warnOnce } from '../output/log'
import { getNodeOptionsArgs } from '../../server/lib/utils' import { getNodeOptionsArgs } from '../../server/lib/utils'
import {
type RelevantCompilerOptions = Pick<CompilerOptions, 'paths' | 'baseUrl'> loadTsConfigOptions,
type RelevantCompilerOptions,
} from '../../lib/typescript/loadTsConfig'
function resolveSWCOptions( function resolveSWCOptions(
cwd: string, cwd: string,
...@@ -26,7 +26,7 @@ function resolveSWCOptions( ...@@ -26,7 +26,7 @@ function resolveSWCOptions(
{ baseUrl: path.resolve(cwd, compilerOptions.baseUrl) } { baseUrl: path.resolve(cwd, compilerOptions.baseUrl) }
: compilerOptions.paths : compilerOptions.paths
? // If paths is given, baseUrl is required. ? // If paths is given, baseUrl is required.
{ baseUrl: cwd } { baseUrl: compilerOptions.pathsBasePath ?? cwd }
: {}), : {}),
}, },
module: { module: {
...@@ -42,85 +42,6 @@ function resolveSWCOptions( ...@@ -42,85 +42,6 @@ function resolveSWCOptions(
} satisfies SWCOptions } satisfies SWCOptions
} }
function resolveExtends(extendsPath: string, currentConfigDir: string): string {
// Relative paths are resolved relative to the current config's directory
if (
extendsPath.startsWith('./') ||
extendsPath.startsWith('../') ||
path.isAbsolute(extendsPath)
) {
const resolved = path.resolve(currentConfigDir, extendsPath)
// TypeScript allows omitting .json extension
if (existsSync(resolved)) {
return resolved
}
if (!resolved.endsWith('.json') && existsSync(resolved + '.json')) {
return resolved + '.json'
}
return resolved
}
// Package paths - use require.resolve to find the package
try {
// Try resolving as a direct path within the package
return require.resolve(extendsPath, { paths: [currentConfigDir] })
} catch {
// If that fails, try appending tsconfig.json for package names like "@tsconfig/node18"
try {
return require.resolve(extendsPath + '/tsconfig.json', {
paths: [currentConfigDir],
})
} catch {
// Return the original path and let it fail later with a clear error
return path.resolve(currentConfigDir, extendsPath)
}
}
}
function loadTsConfigFile(
configPath: string,
visited: Set<string>
): RelevantCompilerOptions {
const resolvedPath = path.resolve(configPath)
if (visited.has(resolvedPath)) {
return {}
}
visited.add(resolvedPath)
if (!existsSync(resolvedPath)) {
return {}
}
const configContent = readFileSync(resolvedPath, 'utf8')
const config = CommentJson.parse(configContent)
const configDir = path.dirname(resolvedPath)
let mergedOptions: RelevantCompilerOptions = {}
// Note that config options from `extends` should get overwritten, not merged
if (config.extends) {
const extendsList = Array.isArray(config.extends)
? config.extends
: [config.extends]
for (const extendsPath of extendsList) {
const parentConfigPath = resolveExtends(extendsPath, configDir)
const parentOptions = loadTsConfigFile(parentConfigPath, visited)
mergedOptions = { ...mergedOptions, ...parentOptions }
}
}
const currentOptions = config.compilerOptions ?? {}
mergedOptions = {
...mergedOptions,
paths: currentOptions.paths ?? mergedOptions.paths,
baseUrl: currentOptions.baseUrl ?? mergedOptions.baseUrl,
}
return mergedOptions
}
async function loadTsConfig(dir: string): Promise<RelevantCompilerOptions> { async function loadTsConfig(dir: string): Promise<RelevantCompilerOptions> {
// NOTE: This doesn't fully cover the edge case for setting // NOTE: This doesn't fully cover the edge case for setting
// "typescript.tsconfigPath" in next config which is currently // "typescript.tsconfigPath" in next config which is currently
...@@ -133,7 +54,7 @@ async function loadTsConfig(dir: string): Promise<RelevantCompilerOptions> { ...@@ -133,7 +54,7 @@ async function loadTsConfig(dir: string): Promise<RelevantCompilerOptions> {
return {} return {}
} }
return loadTsConfigFile(resolvedTsConfigPath, new Set()) return loadTsConfigOptions(resolvedTsConfigPath)
} }
export async function transpileConfig({ export async function transpileConfig({
......
...@@ -10,8 +10,8 @@ import isError from '../lib/is-error' ...@@ -10,8 +10,8 @@ import isError from '../lib/is-error'
import { hrtimeDurationToString } from './duration-to-string' import { hrtimeDurationToString } from './duration-to-string'
/** /**
* typescript will be loaded in "next/lib/verify-typescript-setup" and * TypeScript setup and type checking run in a worker so the compiler's memory
* then passed to "next/lib/typescript/runTypeCheck" as a parameter. * can be released before the rest of the build continues.
* *
* Since it is impossible to pass a function from main thread to a worker, * Since it is impossible to pass a function from main thread to a worker,
* instead of running "next/lib/typescript/runTypeCheck" in a worker, * instead of running "next/lib/typescript/runTypeCheck" in a worker,
...@@ -31,19 +31,21 @@ function verifyAndRunTypeScript( ...@@ -31,19 +31,21 @@ function verifyAndRunTypeScript(
hasPagesDir: boolean, hasPagesDir: boolean,
appDir: string | undefined, appDir: string | undefined,
pagesDir: string | undefined, pagesDir: string | undefined,
debugBuildPaths: { app: string[]; pages: string[] } | undefined debugBuildPaths: { app: string[]; pages: string[] } | undefined,
useTypeScriptCli: boolean,
onFirstCliOutput?: () => void
) { ) {
let impl: typeof import('../lib/verify-typescript-setup').verifyAndRunTypeScript let impl: typeof import('../lib/verify-typescript-setup').verifyAndRunTypeScript
let typeCheckWorker: let typeCheckWorker:
| (Worker & { | (Worker & {
verifyAndRunTypeScript: typeof impl verifyAndRunTypeScriptInWorker: typeof impl
}) })
| undefined | undefined
if (shouldRunTypeCheck) { if (shouldRunTypeCheck && !useTypeScriptCli) {
typeCheckWorker = new Worker( typeCheckWorker = new Worker(
require.resolve('../lib/verify-typescript-setup'), require.resolve('../lib/verify-typescript-setup'),
{ {
exposedMethods: ['verifyAndRunTypeScript'], exposedMethods: ['verifyAndRunTypeScriptInWorker'],
debuggerPortOffset: -1, debuggerPortOffset: -1,
isolatedMemory: false, isolatedMemory: false,
numWorkers: 1, numWorkers: 1,
...@@ -51,10 +53,10 @@ function verifyAndRunTypeScript( ...@@ -51,10 +53,10 @@ function verifyAndRunTypeScript(
maxRetries: 0, maxRetries: 0,
} }
) as typeof typeCheckWorker ) as typeof typeCheckWorker
impl = typeCheckWorker!.verifyAndRunTypeScript impl = typeCheckWorker!.verifyAndRunTypeScriptInWorker
} else { } else {
// When not running typecheck, just run the implementation in-process without spawning a worker, // No worker: either we are not type-checking (just writing setup files), or
// to avoid the overhead of the worker. // the CLI checker runs `tsc` in-process. Avoid the worker overhead.
impl = ( impl = (
require('../lib/verify-typescript-setup') as typeof import('../lib/verify-typescript-setup') require('../lib/verify-typescript-setup') as typeof import('../lib/verify-typescript-setup')
).verifyAndRunTypeScript ).verifyAndRunTypeScript
...@@ -74,14 +76,18 @@ function verifyAndRunTypeScript( ...@@ -74,14 +76,18 @@ function verifyAndRunTypeScript(
appDir, appDir,
pagesDir, pagesDir,
debugBuildPaths, debugBuildPaths,
useTypeScriptCli,
onFirstCliOutput,
}) })
.then((result) => { .then((result) => {
typeCheckWorker?.end() typeCheckWorker?.end()
return result return result
}) })
.catch(() => { .catch(() => {
// The error is already logged in the worker, we simply exit the main thread to prevent the // The error is already logged (in the worker for the API checker, or
// `Jest worker encountered 1 child process exceptions, exceeding retry limit` from showing up // directly for the in-process CLI checker); we simply exit to prevent the
// `Jest worker encountered 1 child process exceptions, exceeding retry
// limit` message from showing up.
process.exit(1) process.exit(1)
}) })
} }
...@@ -106,6 +112,7 @@ export async function startTypeChecking({ ...@@ -106,6 +112,7 @@ export async function startTypeChecking({
debugBuildPaths: { app: string[]; pages: string[] } | undefined debugBuildPaths: { app: string[]; pages: string[] } | undefined
}) { }) {
const ignoreTypeScriptErrors = Boolean(config.typescript.ignoreBuildErrors) const ignoreTypeScriptErrors = Boolean(config.typescript.ignoreBuildErrors)
const useTypeScriptCli = Boolean(config.experimental.useTypeScriptCli)
if (ignoreTypeScriptErrors) { if (ignoreTypeScriptErrors) {
Log.info('Skipping validation of types') Log.info('Skipping validation of types')
...@@ -142,7 +149,12 @@ export async function startTypeChecking({ ...@@ -142,7 +149,12 @@ export async function startTypeChecking({
!!pagesDir, !!pagesDir,
appDir, appDir,
pagesDir, pagesDir,
debugBuildPaths debugBuildPaths,
useTypeScriptCli,
// Stop the spinner before as soon as the subprocess reports output.
useTypeScriptCli && typeCheckingSpinner
? () => typeCheckingSpinner.stop()
: undefined
).then((resolved) => { ).then((resolved) => {
const checkEnd = process.hrtime(typeCheckAndLintStart) const checkEnd = process.hrtime(typeCheckAndLintStart)
return [resolved, checkEnd] as const return [resolved, checkEnd] as const
...@@ -165,6 +177,7 @@ export async function startTypeChecking({ ...@@ -165,6 +177,7 @@ export async function startTypeChecking({
inputFilesCount: verifyResult.result?.inputFilesCount, inputFilesCount: verifyResult.result?.inputFilesCount,
totalFilesCount: verifyResult.result?.totalFilesCount, totalFilesCount: verifyResult.result?.totalFilesCount,
incremental: verifyResult.result?.incremental, incremental: verifyResult.result?.incremental,
typeCheckMode: verifyResult.typeCheckMode,
}) })
) )
} }
......
...@@ -149,6 +149,7 @@ async function runPlaywright( ...@@ -149,6 +149,7 @@ async function runPlaywright(
hasPagesDir: !!pagesDir, hasPagesDir: !!pagesDir,
appDir: appDir || undefined, appDir: appDir || undefined,
pagesDir: pagesDir || undefined, pagesDir: pagesDir || undefined,
useTypeScriptCli: Boolean(nextConfig.experimental.useTypeScriptCli),
}) })
const isUsingTypeScript = !!typeScriptVersion const isUsingTypeScript = !!typeScriptVersion
......
...@@ -54,6 +54,7 @@ const nextTypegen = async ( ...@@ -54,6 +54,7 @@ const nextTypegen = async (
hasPagesDir: !!pagesDir, hasPagesDir: !!pagesDir,
appDir: appDir || undefined, appDir: appDir || undefined,
pagesDir: pagesDir || undefined, pagesDir: pagesDir || undefined,
useTypeScriptCli: Boolean(nextConfig.experimental.useTypeScriptCli),
}) })
console.log('Generating route types...') console.log('Generating route types...')
......
...@@ -9,6 +9,8 @@ export interface MissingDependency { ...@@ -9,6 +9,8 @@ export interface MissingDependency {
* If `exportsRestrict` is false, `${file}` MUST also resolve. * If `exportsRestrict` is false, `${file}` MUST also resolve.
*/ */
pkg: string pkg: string
/** Package specifier to install when it differs from pkg. */
install?: string
/** /**
* If true, the pkg's package.json needs to be resolvable. * If true, the pkg's package.json needs to be resolvable.
* If true, will resolve `file` relative to the real path of the package.json. * If true, will resolve `file` relative to the real path of the package.json.
......
...@@ -32,7 +32,7 @@ export async function installDependencies( ...@@ -32,7 +32,7 @@ export async function installDependencies(
await install( await install(
path.resolve(baseDir), path.resolve(baseDir),
deps.map((dep: MissingDependency) => dep.pkg), deps.map((dep: MissingDependency) => dep.install ?? dep.pkg),
{ devDependencies: dev, isOnline, packageManager } { devDependencies: dev, isOnline, packageManager }
) )
console.log() console.log()
......
import { existsSync, readFileSync, statSync } from 'node:fs'
import path from 'node:path'
import * as CommentJson from 'next/dist/compiled/comment-json'
export type RelevantCompilerOptions = {
paths?: Record<string, string[]>
/** Absolute path for an explicitly configured baseUrl. */
baseUrl?: string
/** Absolute directory containing an inherited paths option without baseUrl. */
pathsBasePath?: string
}
function resolveConfigDirValue(
value: string,
configDir: string,
rootConfigDir: string
): string {
return path.resolve(
configDir,
value.replace(/\$\{configDir\}/g, rootConfigDir)
)
}
function resolveConfigFile(candidate: string): string | undefined {
for (const configPath of [
candidate,
candidate.endsWith('.json') ? undefined : candidate + '.json',
]) {
if (configPath && existsSync(configPath) && statSync(configPath).isFile()) {
return configPath
}
}
}
function resolvePackageTsConfig(
extendsPath: string,
currentConfigDir: string
): string | undefined {
const parts = extendsPath.split('/')
const isPackageRoot = extendsPath.startsWith('@')
? parts.length === 2
: parts.length === 1
if (!isPackageRoot) {
return undefined
}
try {
const packageJsonPath = require.resolve(extendsPath + '/package.json', {
paths: [currentConfigDir],
})
const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8'))
if (packageJson.exports !== undefined) {
try {
const exportedConfig = require.resolve(extendsPath, {
paths: [currentConfigDir],
})
if (path.extname(exportedConfig) === '.json') {
return exportedConfig
}
} catch {}
}
if (typeof packageJson.tsconfig === 'string') {
return resolveConfigFile(
path.resolve(path.dirname(packageJsonPath), packageJson.tsconfig)
)
}
return resolveConfigFile(
path.join(path.dirname(packageJsonPath), 'tsconfig')
)
} catch {}
}
function resolveExtends(extendsPath: string, currentConfigDir: string): string {
if (
extendsPath.startsWith('./') ||
extendsPath.startsWith('../') ||
path.isAbsolute(extendsPath)
) {
const resolved = path.resolve(currentConfigDir, extendsPath)
if (existsSync(resolved)) {
return resolved
}
if (!resolved.endsWith('.json') && existsSync(resolved + '.json')) {
return resolved + '.json'
}
return resolved
}
const packageConfigPath = resolvePackageTsConfig(
extendsPath,
currentConfigDir
)
if (packageConfigPath) {
return packageConfigPath
}
try {
const resolved = require.resolve(extendsPath, { paths: [currentConfigDir] })
if (path.extname(resolved) === '.json') {
return resolved
}
} catch {}
try {
return require.resolve(extendsPath + '/tsconfig.json', {
paths: [currentConfigDir],
})
} catch {
return path.resolve(currentConfigDir, extendsPath)
}
}
function loadTsConfigOptionsRecursive(
configPath: string,
visited: Set<string>,
rootConfigDir: string
): RelevantCompilerOptions {
const resolvedPath = path.resolve(configPath)
if (visited.has(resolvedPath) || !existsSync(resolvedPath)) {
return {}
}
const nextVisited = new Set(visited)
nextVisited.add(resolvedPath)
const configContent = readFileSync(resolvedPath, 'utf8')
const config = CommentJson.parse(configContent)
const configDir = path.dirname(resolvedPath)
let mergedOptions: RelevantCompilerOptions = {}
if (config.extends) {
const extendsList = Array.isArray(config.extends)
? config.extends
: [config.extends]
for (const extendsPath of extendsList) {
const parentConfigPath = resolveExtends(extendsPath, configDir)
const parentOptions = loadTsConfigOptionsRecursive(
parentConfigPath,
nextVisited,
rootConfigDir
)
mergedOptions = { ...mergedOptions, ...parentOptions }
}
}
const currentOptions = config.compilerOptions ?? {}
if (Object.hasOwn(currentOptions, 'paths')) {
mergedOptions.paths = currentOptions.paths
mergedOptions.pathsBasePath = configDir
}
if (
Object.hasOwn(currentOptions, 'baseUrl') &&
typeof currentOptions.baseUrl === 'string'
) {
mergedOptions.baseUrl = resolveConfigDirValue(
currentOptions.baseUrl,
configDir,
rootConfigDir
)
}
if (mergedOptions.baseUrl) {
mergedOptions.pathsBasePath = undefined
}
return mergedOptions
}
/**
* Loads only the tsconfig options Next.js needs outside of the TypeScript API.
* Paths and baseUrl keep the directory they were declared in while resolving
* an extends chain, including arrays of extended configs.
*/
export function loadTsConfigOptions(
configPath: string
): RelevantCompilerOptions {
const resolvedPath = path.resolve(configPath)
return loadTsConfigOptionsRecursive(
resolvedPath,
new Set(),
path.dirname(resolvedPath)
)
}
...@@ -10,7 +10,7 @@ export function missingDepsError( ...@@ -10,7 +10,7 @@ export function missingDepsError(
missingPackages: MissingDependency[] missingPackages: MissingDependency[]
): never { ): never {
const packagesHuman = getOxfordCommaList(missingPackages.map((p) => p.pkg)) const packagesHuman = getOxfordCommaList(missingPackages.map((p) => p.pkg))
const packagesCli = missingPackages.map((p) => p.pkg).join(' ') const packagesCli = missingPackages.map((p) => p.install ?? p.pkg).join(' ')
const packageManager = getPkgManager(dir) const packageManager = getPkgManager(dir)
const removalMsg = const removalMsg =
......
...@@ -10,8 +10,8 @@ import { warn } from '../../build/output/log' ...@@ -10,8 +10,8 @@ import { warn } from '../../build/output/log'
export interface TypeCheckResult { export interface TypeCheckResult {
hasWarnings: boolean hasWarnings: boolean
warnings?: string[] warnings?: string[]
inputFilesCount: number inputFilesCount?: number
totalFilesCount: number totalFilesCount?: number
incremental: boolean incremental: boolean
} }
......
import path from 'node:path'
import { CompileError } from '../compile-error'
import type { TypeCheckResult } from './runTypeCheck'
import {
getTypeScriptConfigurationCli,
runTypeScriptCli,
} from './runTypeScriptCli'
export async function runTypeCheckCli({
baseDir,
tsConfigPath,
tscPath,
cacheDir,
onFirstOutput,
}: {
baseDir: string
tsConfigPath: string
tscPath: string
cacheDir?: string
/**
* Called once when `tsc` first produces output. Used to stop the build
* spinner so it does not sit above the diagnostics.
*/
onFirstOutput?: () => void
}): Promise<TypeCheckResult> {
const configuration = await getTypeScriptConfigurationCli({
baseDir,
tsConfigPath,
tscPath,
})
const incremental = Boolean(
configuration.compilerOptions.incremental ||
configuration.compilerOptions.composite
)
const args = [
'--project',
tsConfigPath,
'--noEmit',
'--declarationMap',
'false',
'--emitDeclarationOnly',
'false',
]
if (incremental && cacheDir) {
args.push('--tsBuildInfoFile', path.join(cacheDir, '.tsbuildinfo'))
}
const result = await runTypeScriptCli({
cwd: baseDir,
tscPath,
args,
onFirstOutput,
})
if (result.exitCode !== 0) {
throw new CompileError()
}
return {
hasWarnings: false,
incremental,
}
}
import type { ChildProcess } from 'node:child_process'
import { EventEmitter } from 'node:events'
import { PassThrough } from 'node:stream'
const mockSpawn = jest.fn()
jest.mock('next/dist/compiled/cross-spawn', () => ({
__esModule: true,
default: (...args: unknown[]) => mockSpawn(...args),
}))
const { runTypeScriptCli } =
require('./runTypeScriptCli') as typeof import('./runTypeScriptCli')
const processEvents = ['exit', 'SIGINT', 'SIGTERM', 'SIGHUP'] as const
type ProcessEvent = (typeof processEvents)[number]
type ProcessListener = (...args: any[]) => void
function getProcessListeners(event: ProcessEvent): ProcessListener[] {
return (process as EventEmitter).listeners(event) as ProcessListener[]
}
class MockChildProcess extends EventEmitter {
pid = 4321
killed = false
kill = jest.fn(() => true)
stdout = new PassThrough()
stderr = new PassThrough()
}
describe('runTypeScriptCli', () => {
let child: MockChildProcess
let originalListeners: Map<ProcessEvent, ProcessListener[]>
let processKill: jest.SpiedFunction<typeof process.kill>
beforeEach(() => {
child = new MockChildProcess()
mockSpawn.mockReset().mockReturnValue(child as unknown as ChildProcess)
processKill = jest.spyOn(process, 'kill').mockReturnValue(true)
originalListeners = new Map(
processEvents.map((event) => [event, getProcessListeners(event)])
)
})
afterEach(() => {
for (const event of processEvents) {
const listenersBeforeTest = originalListeners.get(event)!
for (const listener of getProcessListeners(event)) {
if (!listenersBeforeTest.includes(listener)) {
process.off(event, listener)
}
}
}
processKill.mockRestore()
})
function getAddedListener(event: ProcessEvent): ProcessListener {
const listenersBeforeTest = originalListeners.get(event)!
const addedListener = getProcessListeners(event).find(
(listener) => !listenersBeforeTest.includes(listener)
)
expect(addedListener).toBeDefined()
return addedListener!
}
function expectListenersRestored() {
for (const event of processEvents) {
expect(getProcessListeners(event)).toEqual(originalListeners.get(event))
}
}
it('spawns tsc detached with piped stdio and resolves with the exit code', async () => {
const resultPromise = runTypeScriptCli({
cwd: '/project',
tscPath: '/project/node_modules/typescript/bin/tsc',
args: ['--noEmit'],
})
expect(mockSpawn).toHaveBeenCalledWith(
process.execPath,
['/project/node_modules/typescript/bin/tsc', '--noEmit'],
expect.objectContaining({
cwd: '/project',
detached: process.platform !== 'win32',
shell: false,
stdio: ['ignore', 'pipe', 'pipe'],
})
)
child.emit('close', 0, null)
await expect(resultPromise).resolves.toMatchObject({
exitCode: 0,
signal: null,
})
expectListenersRestored()
})
it('forwards output as it arrives, preserving stdout/stderr interleaving, and stops the spinner on the first byte', async () => {
const stdoutWrite = jest
.spyOn(process.stdout, 'write')
.mockImplementation(() => true)
const stderrWrite = jest
.spyOn(process.stderr, 'write')
.mockImplementation(() => true)
const onFirstOutput = jest.fn()
try {
const resultPromise = runTypeScriptCli({
cwd: '/project',
tscPath: '/project/node_modules/typescript/bin/tsc',
args: ['--noEmit'],
onFirstOutput,
})
child.stdout.write('checking a\n')
child.stderr.write('warning b\n')
child.stdout.write('checking c\n')
child.emit('close', 0, null)
await expect(resultPromise).resolves.toMatchObject({ exitCode: 0 })
expect(onFirstOutput).toHaveBeenCalledTimes(1)
expect(stdoutWrite).toHaveBeenNthCalledWith(1, 'checking a\n')
expect(stderrWrite).toHaveBeenNthCalledWith(1, 'warning b\n')
expect(stdoutWrite).toHaveBeenNthCalledWith(2, 'checking c\n')
} finally {
stdoutWrite.mockRestore()
stderrWrite.mockRestore()
}
expectListenersRestored()
})
it('SIGKILLs the whole process group on process exit', async () => {
// The native compiler ignores catchable signals, so teardown must SIGKILL
// the process group (negative pid) to reap it.
if (process.platform === 'win32') {
return
}
const resultPromise = runTypeScriptCli({
cwd: '/project',
tscPath: '/project/node_modules/typescript/bin/tsc',
args: ['--noEmit'],
})
getAddedListener('exit')()
expect(processKill).toHaveBeenCalledWith(-child.pid, 'SIGKILL')
child.emit('close', null, 'SIGKILL')
await expect(resultPromise).resolves.toMatchObject({
exitCode: 1,
signal: 'SIGKILL',
})
expectListenersRestored()
})
it('terminates the child only once', async () => {
if (process.platform === 'win32') {
return
}
const resultPromise = runTypeScriptCli({
cwd: '/project',
tscPath: '/project/node_modules/typescript/bin/tsc',
args: ['--noEmit'],
})
const terminate = getAddedListener('exit')
terminate()
terminate()
expect(processKill).toHaveBeenCalledTimes(1)
child.emit('close', null, 'SIGKILL')
await resultPromise
expectListenersRestored()
})
it('reaps the child and exits on a termination signal', async () => {
// Node.js does not fire `exit` on signal termination, so SIGINT/SIGTERM/
// SIGHUP must be handled explicitly or the native compiler would be left
// running.
if (process.platform === 'win32') {
return
}
const processExit = jest
.spyOn(process, 'exit')
.mockImplementation((() => undefined) as never)
try {
const resultPromise = runTypeScriptCli({
cwd: '/project',
tscPath: '/project/node_modules/typescript/bin/tsc',
args: ['--noEmit'],
})
getAddedListener('SIGINT')()
expect(processKill).toHaveBeenCalledWith(-child.pid, 'SIGKILL')
expect(processExit).toHaveBeenCalledWith(1)
child.emit('close', null, 'SIGKILL')
await resultPromise
} finally {
processExit.mockRestore()
}
expectListenersRestored()
})
it('rejects spawn failures and cleans up all listeners', async () => {
const error = new Error('failed to spawn tsc')
const resultPromise = runTypeScriptCli({
cwd: '/project',
tscPath: '/project/node_modules/typescript/bin/tsc',
args: ['--noEmit'],
})
const rejection = resultPromise.catch((spawnError) => spawnError)
child.emit('error', error)
await expect(rejection).resolves.toBe(error)
expectListenersRestored()
})
it('decodes captured UTF-8 output across chunk boundaries', async () => {
const resultPromise = runTypeScriptCli({
cwd: '/project',
tscPath: '/project/node_modules/typescript/bin/tsc',
args: ['--showConfig'],
captureOutput: true,
})
const stdout = '{"compilerOptions":{"baseUrl":"café"}}'
const stdoutBuffer = Buffer.from(stdout)
const splitIndex = stdoutBuffer.indexOf('é') + 1
child.stdout.write(stdoutBuffer.subarray(0, splitIndex))
child.stdout.write(stdoutBuffer.subarray(splitIndex))
child.stderr.write(Buffer.from('avertissement 💡'))
child.emit('close', 0, null)
await expect(resultPromise).resolves.toMatchObject({
exitCode: 0,
stdout,
stderr: 'avertissement 💡',
})
expectListenersRestored()
})
})
import { existsSync, readFileSync } from 'node:fs'
import path from 'node:path'
import { spawnSync } from 'node:child_process'
import spawn from 'next/dist/compiled/cross-spawn'
import { bold } from '../picocolors'
import { resolveFrom } from '../resolve-from'
export interface TypeScriptPackageInfo {
packageJsonPath: string
packageDir: string
version: string
apiPath?: string
tscPath?: string
}
export function getTypeScriptPackageInfo(
baseDir: string
): TypeScriptPackageInfo | null {
let packageJsonPath: string
try {
packageJsonPath = resolveFrom(baseDir, 'typescript/package.json')
} catch {
return null
}
const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8')) as {
version: string
type?: string
bin?: string | Record<string, string>
}
const packageDir = path.dirname(packageJsonPath)
const apiPath = path.join(packageDir, 'lib', 'typescript.js')
const tscBin =
typeof packageJson.bin === 'string' ? packageJson.bin : packageJson.bin?.tsc
const tscBinPath = tscBin ? path.resolve(packageDir, tscBin) : undefined
let tscPath = tscBinPath
if (
tscBinPath &&
existsSync(tscBinPath) &&
packageJson.type === 'module' &&
path.extname(tscBinPath) === ''
) {
// TypeScript 7's extensionless ESM bin wrapper cannot be used as Node's
// main entry point on Node.js 20.9. Its imported JS entry is the same CLI
// wrapper and works across all supported Node.js versions.
const tscJsPath = path.join(packageDir, 'lib', 'tsc.js')
if (existsSync(tscJsPath)) {
tscPath = tscJsPath
}
}
return {
packageJsonPath,
packageDir,
version: packageJson.version,
apiPath: existsSync(apiPath) ? apiPath : undefined,
tscPath: tscPath && existsSync(tscPath) ? tscPath : undefined,
}
}
export function hasNativeTypeScriptPreview(baseDir: string): boolean {
try {
resolveFrom(baseDir, '@typescript/native-preview/package.json')
return true
} catch {
return false
}
}
export function getTypeScriptApiMissingError(version: string): Error {
return new Error(
`TypeScript ${version} does not provide the compiler API required by Next.js. ` +
`Enable ${bold('experimental.useTypeScriptCli')} in your Next.js config to use the TypeScript CLI, ` +
`or install TypeScript 6 instead.`
)
}
export interface TypeScriptCliResult {
exitCode: number
signal: NodeJS.Signals | null
stdout: string
stderr: string
}
const terminationSignals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGHUP']
export function runTypeScriptCli({
cwd,
tscPath,
args,
captureOutput = false,
onFirstOutput,
}: {
cwd: string
tscPath: string
args: string[]
/**
* Accumulate stdout/stderr into the resolved result instead of forwarding it
* to this process's stdout/stderr (for e.g. parsing `--showConfig` output).
*/
captureOutput?: boolean
/**
* Called once, on the first chunk of forwarded output. Used to stop the build
* spinner before `tsc`'s diagnostics appear. Not called when capturing.
*/
onFirstOutput?: () => void
}): Promise<TypeScriptCliResult> {
return new Promise((resolve, reject) => {
const child = spawn(process.execPath, [tscPath, ...args], {
cwd,
// TypeScript 7's Node wrapper starts the native compiler synchronously
// on older Node.js releases. A separate process group lets termination
// reach both processes instead of orphaning the native compiler.
detached: process.platform !== 'win32',
shell: false,
stdio: ['ignore', 'pipe', 'pipe'],
env: {
...process.env,
// Piping stdio makes `tsc` disable colored/pretty diagnostics. Restore
// them when we are forwarding output to a TTY (not capturing it for
// parsing, e.g. `--showConfig`).
...(!captureOutput && process.stdout.isTTY
? { FORCE_COLOR: '1' }
: undefined),
},
})
let stdout = ''
let stderr = ''
child.stdout?.setEncoding('utf8')
child.stderr?.setEncoding('utf8')
if (captureOutput) {
child.stdout?.on('data', (chunk: string) => {
stdout += chunk
})
child.stderr?.on('data', (chunk: string) => {
stderr += chunk
})
} else {
const forward = (dest: NodeJS.WriteStream, chunk: string) => {
onFirstOutput?.()
onFirstOutput = undefined // ensure we don't call it again
dest.write(chunk)
}
child.stdout?.on('data', (chunk: string) => {
forward(process.stdout, chunk)
})
child.stderr?.on('data', (chunk: string) => {
forward(process.stderr, chunk)
})
}
let terminationRequested = false
const terminateChild = () => {
if (terminationRequested || child.killed || child.pid === undefined) {
return
}
terminationRequested = true
// The native compiler ignores SIGTERM and SIGINT, so send a kill signal.
// Target the whole process group so the signal reaches the native compiler whether
// it is a grandchild or a direct child.
// https://github.com/microsoft/typescript-go/pull/4592 should improve this in the long run
if (process.platform === 'win32') {
spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], {
stdio: 'ignore',
windowsHide: true,
})
} else {
try {
// https://www.youtube.com/watch?v=Fow7iUaKrq4
process.kill(-child.pid, 'SIGKILL')
} catch {
// The process may have exited between the lifecycle event and kill.
}
}
}
const terminateOnExit = () => terminateChild()
process.once('exit', terminateOnExit)
const handler = () => {
terminateChild()
process.exit(1)
}
for (const signal of terminationSignals) {
process.once(signal, handler)
}
const cleanup = () => {
process.off('exit', terminateOnExit)
for (const signal of terminationSignals) {
process.off(signal, handler)
}
}
let settled = false
const finish = (settle: () => void) => {
if (settled) {
return
}
settled = true
cleanup()
settle()
}
child.on('error', (error) => {
finish(() => reject(error))
})
child.on('close', (code, signal) => {
finish(() => {
resolve({
exitCode: code ?? 1,
signal,
stdout,
stderr,
})
})
})
})
}
export async function getTypeScriptConfigurationCli({
baseDir,
tsConfigPath,
tscPath,
}: {
baseDir: string
tsConfigPath: string
tscPath: string
}): Promise<{ compilerOptions: Record<string, any> }> {
const result = await runTypeScriptCli({
cwd: baseDir,
tscPath,
args: ['--showConfig', '--project', tsConfigPath, '--pretty', 'false'],
captureOutput: true,
})
if (result.exitCode !== 0) {
throw new Error(
[result.stdout, result.stderr].filter(Boolean).join('\n').trim()
)
}
try {
return JSON.parse(result.stdout)
} catch (cause) {
throw new Error(`Could not parse output from TypeScript's --showConfig.`, {
cause,
})
}
}
import { bold, cyan, red, yellow } from './picocolors' import { bold, cyan, red, yellow } from './picocolors'
import path, { join } from 'path' import path from 'path'
import { hasNecessaryDependencies } from './has-necessary-dependencies' import { hasNecessaryDependencies } from './has-necessary-dependencies'
import type { import type {
...@@ -17,16 +17,26 @@ import { writeConfigurationDefaults } from './typescript/writeConfigurationDefau ...@@ -17,16 +17,26 @@ import { writeConfigurationDefaults } from './typescript/writeConfigurationDefau
import { installDependencies } from './install-dependencies' import { installDependencies } from './install-dependencies'
import { isCI } from '../server/ci-info' import { isCI } from '../server/ci-info'
import { missingDepsError } from './typescript/missingDependencyError' import { missingDepsError } from './typescript/missingDependencyError'
import { resolveFrom } from './resolve-from' import {
getTypeScriptApiMissingError,
getTypeScriptPackageInfo,
hasNativeTypeScriptPreview,
} from './typescript/runTypeScriptCli'
const typescriptPackage: MissingDependency = { const typescriptApiPackage: MissingDependency = {
file: 'typescript/lib/typescript.js', file: 'typescript/lib/typescript.js',
pkg: 'typescript', pkg: 'typescript',
install: 'typescript@^6.0.0',
exportsRestrict: true, exportsRestrict: true,
} }
const requiredPackages: MissingDependency[] = [ const typescriptCliPackage: MissingDependency = {
typescriptPackage, file: 'typescript/bin/tsc',
pkg: 'typescript',
exportsRestrict: true,
}
const requiredTypePackages: MissingDependency[] = [
{ {
file: '@types/react/index.d.ts', file: '@types/react/index.d.ts',
pkg: '@types/react', pkg: '@types/react',
...@@ -39,20 +49,6 @@ const requiredPackages: MissingDependency[] = [ ...@@ -39,20 +49,6 @@ const requiredPackages: MissingDependency[] = [
}, },
] ]
/**
* Check if @typescript/native-preview is installed as an alternative TypeScript compiler.
* This is a Go-based native TypeScript compiler that can be used instead of the standard
* TypeScript package for faster compilation.
*/
function hasNativeTypeScriptPreview(dir: string): boolean {
try {
resolveFrom(dir, '@typescript/native-preview/package.json')
return true
} catch {
return false
}
}
export async function verifyAndRunTypeScript({ export async function verifyAndRunTypeScript({
dir, dir,
distDir, distDir,
...@@ -67,6 +63,8 @@ export async function verifyAndRunTypeScript({ ...@@ -67,6 +63,8 @@ export async function verifyAndRunTypeScript({
appDir, appDir,
pagesDir, pagesDir,
debugBuildPaths, debugBuildPaths,
useTypeScriptCli = false,
onFirstCliOutput,
}: { }: {
dir: string dir: string
distDir: string distDir: string
...@@ -81,9 +79,20 @@ export async function verifyAndRunTypeScript({ ...@@ -81,9 +79,20 @@ export async function verifyAndRunTypeScript({
appDir?: string appDir?: string
pagesDir?: string pagesDir?: string
debugBuildPaths?: { app?: string[]; pages?: string[] } debugBuildPaths?: { app?: string[]; pages?: string[] }
}): Promise<{ result?: TypeCheckResult; version: string | null }> { useTypeScriptCli?: boolean
/**
* Called once when the CLI checker first produces output, so the caller can
* stop the build spinner. Only used on the in-process CLI path.
*/
onFirstCliOutput?: () => void
}): Promise<{
result?: TypeCheckResult
version: string | null
typeCheckMode: 'typescript-api' | 'typescript-cli'
}> {
const tsConfigFileName = tsconfigPath || 'tsconfig.json' const tsConfigFileName = tsconfigPath || 'tsconfig.json'
const resolvedTsConfigPath = path.join(dir, tsConfigFileName) const resolvedTsConfigPath = path.join(dir, tsConfigFileName)
const typeCheckMode = useTypeScriptCli ? 'typescript-cli' : 'typescript-api'
// Construct intentDirs from appDir and pagesDir for getTypeScriptIntent // Construct intentDirs from appDir and pagesDir for getTypeScriptIntent
const intentDirs = [pagesDir, appDir].filter(Boolean) as string[] const intentDirs = [pagesDir, appDir].filter(Boolean) as string[]
...@@ -92,11 +101,26 @@ export async function verifyAndRunTypeScript({ ...@@ -92,11 +101,26 @@ export async function verifyAndRunTypeScript({
// Check if the project uses TypeScript: // Check if the project uses TypeScript:
const intent = await getTypeScriptIntent(dir, intentDirs, tsConfigFileName) const intent = await getTypeScriptIntent(dir, intentDirs, tsConfigFileName)
if (!intent) { if (!intent) {
return { version: null } return { version: null, typeCheckMode }
} }
// Check if @typescript/native-preview is installed as an alternative // Check if @typescript/native-preview is installed as an alternative
const hasNativePreview = hasNativeTypeScriptPreview(dir) const hasNativePreview = hasNativeTypeScriptPreview(dir)
const installedTypeScript = getTypeScriptPackageInfo(dir)
if (
!useTypeScriptCli &&
!hasNativePreview &&
installedTypeScript &&
!installedTypeScript.apiPath
) {
throw getTypeScriptApiMissingError(installedTypeScript.version)
}
const requiredPackages: MissingDependency[] = [
useTypeScriptCli ? typescriptCliPackage : typescriptApiPackage,
...requiredTypePackages,
]
// Ensure TypeScript and necessary `@types/*` are installed: // Ensure TypeScript and necessary `@types/*` are installed:
let deps: NecessaryDependencies = hasNecessaryDependencies( let deps: NecessaryDependencies = hasNecessaryDependencies(
...@@ -107,7 +131,7 @@ export async function verifyAndRunTypeScript({ ...@@ -107,7 +131,7 @@ export async function verifyAndRunTypeScript({
// If @typescript/native-preview is installed and only the typescript package is missing, // If @typescript/native-preview is installed and only the typescript package is missing,
// we can skip auto-installing typescript since the native preview provides TS compilation. // we can skip auto-installing typescript since the native preview provides TS compilation.
// However, we still need @types/react and @types/node for type checking. // However, we still need @types/react and @types/node for type checking.
if (hasNativePreview && deps.missing?.length > 0) { if (!useTypeScriptCli && hasNativePreview && deps.missing?.length > 0) {
const missingWithoutTypescript = deps.missing.filter( const missingWithoutTypescript = deps.missing.filter(
(dep) => dep.pkg !== 'typescript' (dep) => dep.pkg !== 'typescript'
) )
...@@ -133,7 +157,7 @@ export async function verifyAndRunTypeScript({ ...@@ -133,7 +157,7 @@ export async function verifyAndRunTypeScript({
typedRoutes, typedRoutes,
}) })
return { version: null } return { version: null, typeCheckMode }
} }
// If there are other missing deps besides typescript, only install those // If there are other missing deps besides typescript, only install those
...@@ -180,13 +204,21 @@ export async function verifyAndRunTypeScript({ ...@@ -180,13 +204,21 @@ export async function verifyAndRunTypeScript({
deps = hasNecessaryDependencies(dir, requiredPackages) deps = hasNecessaryDependencies(dir, requiredPackages)
} }
// Load TypeScript after we're sure it exists: const typeScriptPackage = getTypeScriptPackageInfo(dir)
const tsPackageJsonPath = deps.resolved.get( const typeScriptPath = useTypeScriptCli
join('typescript', 'package.json') ? typeScriptPackage?.tscPath
)! : typeScriptPackage?.apiPath
const typescriptPackageJson = require(tsPackageJsonPath)
const typescriptVersion = typescriptPackageJson.version if (!typeScriptPackage || !typeScriptPath) {
missingDepsError(
dir,
deps.missing.length > 0
? deps.missing
: [useTypeScriptCli ? typescriptCliPackage : typescriptApiPackage]
)
}
const typescriptVersion = typeScriptPackage.version
if (semver.lt(typescriptVersion, '5.1.0')) { if (semver.lt(typescriptVersion, '5.1.0')) {
log.warn( log.warn(
...@@ -218,6 +250,23 @@ export async function verifyAndRunTypeScript({ ...@@ -218,6 +250,23 @@ export async function verifyAndRunTypeScript({
let result let result
if (shouldRunTypeCheck) { if (shouldRunTypeCheck) {
if (useTypeScriptCli) {
if (debugBuildPaths) {
log.warn(
'`experimental.useTypeScriptCli` checks the complete TypeScript project; `--debug-build-paths` does not limit type checking.'
)
}
const { runTypeCheckCli } =
require('./typescript/runTypeCheckCli') as typeof import('./typescript/runTypeCheckCli')
result = await runTypeCheckCli({
baseDir: dir,
tsConfigPath: resolvedTsConfigPath,
tscPath: typeScriptPath,
cacheDir,
onFirstOutput: onFirstCliOutput,
})
} else {
const { runTypeCheck } = const { runTypeCheck } =
require('./typescript/runTypeCheck') as typeof import('./typescript/runTypeCheck') require('./typescript/runTypeCheck') as typeof import('./typescript/runTypeCheck')
// Install native bindings so that code frame rendering works in the worker // Install native bindings so that code frame rendering works in the worker
...@@ -225,9 +274,8 @@ export async function verifyAndRunTypeScript({ ...@@ -225,9 +274,8 @@ export async function verifyAndRunTypeScript({
require('../build/swc/install-bindings') as typeof import('../build/swc/install-bindings') require('../build/swc/install-bindings') as typeof import('../build/swc/install-bindings')
await installBindings() await installBindings()
const tsPath = deps.resolved.get('typescript')!
const typescript = (await Promise.resolve( const typescript = (await Promise.resolve(
require(tsPath) require(typeScriptPath)
)) as typeof import('typescript') )) as typeof import('typescript')
// Verify the project passes type-checking before we go to webpack phase: // Verify the project passes type-checking before we go to webpack phase:
...@@ -242,31 +290,46 @@ export async function verifyAndRunTypeScript({ ...@@ -242,31 +290,46 @@ export async function verifyAndRunTypeScript({
debugBuildPaths debugBuildPaths
) )
} }
return { result, version: typescriptVersion } }
return { result, version: typescriptVersion, typeCheckMode }
} catch (err) { } catch (err) {
// These are special errors that should not show a stack trace: // Print the user-facing message here and rethrow. This function runs both
// in-process (next dev / next test / next typegen, and the CLI type-check
// during build) and inside a jest worker (the TypeScript-API type-check
// during build). A thrown error does not survive the worker boundary — the
// parent only sees `Call retries were exceeded` — so the message must be
// printed on this side. The caller decides what to do with the throw (exit,
// or tolerate it as `next dev` does on re-verification).
if (err instanceof CompileError) { if (err instanceof CompileError) {
// The checker already printed its diagnostics.
console.error(red('Failed to type check.\n')) console.error(red('Failed to type check.\n'))
if (err.message) {
console.error(err.message) console.error(err.message)
process.exit(1)
} }
} else if (err instanceof Error) {
/**
* verifyAndRunTypeScript can be either invoked directly in the main thread (during next dev / next lint)
* or run in a worker (during next build). In the latter case, we need to print the error message, as the
* parent process will only receive an `Jest worker encountered 1 child process exceptions, exceeding retry limit`.
*/
// we are in a worker, print the error message and exit the process
if (process.env.IS_NEXT_WORKER) {
if (err instanceof Error) {
console.error(err.message) console.error(err.message)
} else { } else {
console.error(err) console.error(err)
} }
process.exit(1)
}
// we are in the main thread, throw the error and it will be handled by the caller
throw err throw err
} }
} }
/**
* Worker entrypoint used by `next build` for the TypeScript-API type-check.
* `verifyAndRunTypeScript` has already printed any error, so on failure we exit
* the worker directly rather than rethrowing: a thrown error would be retried by
* jest-worker and surface in the parent as the unhelpful
* `Jest worker encountered 1 child process exceptions, exceeding retry limit`.
*/
export async function verifyAndRunTypeScriptInWorker(
options: Parameters<typeof verifyAndRunTypeScript>[0]
): ReturnType<typeof verifyAndRunTypeScript> {
try {
return await verifyAndRunTypeScript(options)
} catch {
// The error was already printed by `verifyAndRunTypeScript`.
// Kill the worker with a non-zero exit code.
process.exit(1)
}
}
...@@ -359,6 +359,7 @@ export const experimentalSchema = { ...@@ -359,6 +359,7 @@ export const experimentalSchema = {
optimizePackageImports: z.array(z.string()).optional(), optimizePackageImports: z.array(z.string()).optional(),
optimizeServerReact: z.boolean().optional(), optimizeServerReact: z.boolean().optional(),
strictRouteTypes: z.boolean().optional(), strictRouteTypes: z.boolean().optional(),
useTypeScriptCli: z.boolean().optional(),
clientTraceMetadata: z.array(z.string()).optional(), clientTraceMetadata: z.array(z.string()).optional(),
serverMinification: z.boolean().optional(), serverMinification: z.boolean().optional(),
serverSourceMaps: z.boolean().optional(), serverSourceMaps: z.boolean().optional(),
......
...@@ -547,6 +547,12 @@ export interface ExperimentalConfig { ...@@ -547,6 +547,12 @@ export interface ExperimentalConfig {
*/ */
strictRouteTypes?: boolean strictRouteTypes?: boolean
/**
* Runs the project-local TypeScript CLI instead of using TypeScript's
* programmatic API for build-time type checking and config loading.
*/
useTypeScriptCli?: boolean
/** /**
* Displays an indicator when a React Transition has no other indicator rendered. * Displays an indicator when a React Transition has no other indicator rendered.
* This includes displaying an indicator on client-side navigations. * This includes displaying an indicator on client-side navigations.
...@@ -1794,6 +1800,7 @@ export const defaultConfig = Object.freeze({ ...@@ -1794,6 +1800,7 @@ export const defaultConfig = Object.freeze({
webpackMemoryOptimizations: false, webpackMemoryOptimizations: false,
optimizeServerReact: true, optimizeServerReact: true,
strictRouteTypes: false, strictRouteTypes: false,
useTypeScriptCli: false,
viewTransition: false, viewTransition: false,
removeUncaughtErrorAndRejectionListeners: false, removeUncaughtErrorAndRejectionListeners: false,
validateRSCRequestHeaders: !!( validateRSCRequestHeaders: !!(
......
...@@ -164,6 +164,7 @@ async function verifyTypeScript(opts: SetupOpts) { ...@@ -164,6 +164,7 @@ async function verifyTypeScript(opts: SetupOpts) {
hasPagesDir: !!opts.pagesDir, hasPagesDir: !!opts.pagesDir,
appDir: opts.appDir, appDir: opts.appDir,
pagesDir: opts.pagesDir, pagesDir: opts.pagesDir,
useTypeScriptCli: Boolean(opts.nextConfig.experimental.useTypeScriptCli),
}) })
if (verifyResult.version) { if (verifyResult.version) {
......
...@@ -15,6 +15,7 @@ type EventTypeCheckCompleted = { ...@@ -15,6 +15,7 @@ type EventTypeCheckCompleted = {
inputFilesCount?: number inputFilesCount?: number
totalFilesCount?: number totalFilesCount?: number
incremental?: boolean incremental?: boolean
typeCheckMode: 'typescript-api' | 'typescript-cli'
} }
export function eventTypeCheckCompleted(event: EventTypeCheckCompleted): { export function eventTypeCheckCompleted(event: EventTypeCheckCompleted): {
......
# TypeScript 7 is intentionally tested immediately after release.
minimum-release-age=0
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { message } from '@fixture/message'
export default function Page() {
return <p>{message}</p>
}
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"paths": {
"@fixture/*": ["../src/*"]
}
}
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
useTypeScriptCli: true,
},
typescript: {
tsconfigPath: 'tsconfig.build.json',
},
}
module.exports = nextConfig
export const message = 'hello from an inherited path alias'
{
"extends": "./config/tsconfig.paths.json",
"compilerOptions": {
"incremental": true,
"plugins": [
{
"name": "next"
}
]
},
"include": [
"next-env.d.ts",
"app/**/*.ts",
"app/**/*.tsx",
"src/**/*.ts",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
],
"exclude": ["node_modules"]
}
import { nextTestSetup } from 'e2e-utils'
const cliConfig = `module.exports = {
experimental: { useTypeScriptCli: true },
typescript: { tsconfigPath: 'tsconfig.build.json' },
}
`
const apiConfig = `module.exports = {
typescript: { tsconfigPath: 'tsconfig.build.json' },
}
`
const typeError = `export const invalidValue: number = 'not a number'
`
describe('experimental TypeScript CLI backend', () => {
describe('TypeScript 7', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
dependencies: {
typescript: '7.0.2',
},
})
if (skipped) return
let originalTsConfig: string
beforeAll(async () => {
originalTsConfig = await next.readFile('tsconfig.build.json')
})
afterEach(async () => {
await next.patchFile('next.config.js', cliConfig)
await next.patchFile('tsconfig.build.json', originalTsConfig)
await next.deleteFile('src/type-error.ts').catch(() => {})
await next
.deleteFile('.next/dev/types/stale-type-error.test.ts')
.catch(() => {})
await next.deleteFile('.next/cache/.tsbuildinfo').catch(() => {})
})
it('builds with the native CLI, a custom tsconfig, and inherited paths', async () => {
const result = await next.build({
env: { NEXT_TELEMETRY_DEBUG: '1' },
})
expect(result.exitCode).toBe(0)
expect(result.cliOutput).toContain('NEXT_TYPE_CHECK_COMPLETED')
expect(result.cliOutput).toContain('"typeCheckMode": "typescript-cli"')
expect(result.cliOutput).not.toContain('"inputFilesCount"')
expect(result.cliOutput).not.toContain('"totalFilesCount"')
expect(await next.hasFile('.next/cache/.tsbuildinfo')).toBe(true)
})
it('prints raw TypeScript CLI diagnostics', async () => {
await next.patchFile('src/type-error.ts', typeError)
const result = await next.build()
expect(result.exitCode).toBe(1)
expect(result.cliOutput).toContain('src/type-error.ts')
expect(result.cliOutput).toContain('error TS2322')
expect(result.cliOutput).toContain(
"Type 'string' is not assignable to type 'number'"
)
})
it('does not create incremental state when incremental is disabled', async () => {
await next.patchFile(
'tsconfig.build.json',
originalTsConfig.replace('"incremental": true', '"incremental": false')
)
const result = await next.build()
expect(result.exitCode).toBe(0)
expect(await next.hasFile('.next/cache/.tsbuildinfo')).toBe(false)
})
it('honors typescript.ignoreBuildErrors', async () => {
await next.patchFile('src/type-error.ts', typeError)
await next.patchFile(
'next.config.js',
`module.exports = {
experimental: { useTypeScriptCli: true },
typescript: {
ignoreBuildErrors: true,
tsconfigPath: 'tsconfig.build.json',
},
}
`
)
const result = await next.build()
expect(result.exitCode).toBe(0)
expect(result.cliOutput).toContain('Skipping validation of types')
})
it('checks the complete project with --debug-build-paths', async () => {
await next.patchFile(
'.next/dev/types/stale-type-error.test.ts',
typeError
)
const result = await next.build({
args: ['--debug-build-paths', 'app/page.tsx'],
})
expect(result.exitCode).toBe(1)
expect(result.cliOutput).toContain(
'`experimental.useTypeScriptCli` checks the complete TypeScript project; `--debug-build-paths` does not limit type checking.'
)
expect(result.cliOutput).toContain(
'.next/dev/types/stale-type-error.test.ts'
)
expect(result.cliOutput).toContain('error TS2322')
})
})
describe('TypeScript 7 without the opt-in', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
dependencies: {
typescript: '7.0.2',
},
})
if (skipped) return
it('fails with actionable migration guidance', async () => {
await next.patchFile('next.config.js', apiConfig)
const result = await next.build()
expect(result.exitCode).toBe(1)
expect(result.cliOutput).toContain(
'TypeScript 7.0.2 does not provide the compiler API required by Next.js'
)
expect(result.cliOutput).toContain('experimental.useTypeScriptCli')
expect(result.cliOutput).toContain('install TypeScript 6 instead')
})
})
describe('TypeScript 6', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
dependencies: {
typescript: '6.0.2',
},
})
if (skipped) return
it('uses the same project-local tsc entry point', async () => {
const result = await next.build()
expect(result.exitCode).toBe(0)
expect(await next.hasFile('.next/cache/.tsbuildinfo')).toBe(true)
})
})
})
export const shouldNotBeChecked: number = 'custom tsconfig was ignored'
...@@ -29,6 +29,47 @@ describe('ci-missing-typescript-deps', () => { ...@@ -29,6 +29,47 @@ describe('ci-missing-typescript-deps', () => {
`It looks like you're trying to use TypeScript but do not have the required package(s) installed.` `It looks like you're trying to use TypeScript but do not have the required package(s) installed.`
) )
expect(next.cliOutput).toContain(`Please install`) expect(next.cliOutput).toContain(`Please install`)
expect(next.cliOutput).toContain(
'pnpm install --save-dev typescript@^6.0.0'
)
expect(next.cliOutput).not.toContain('Call retries were exceeded')
expect(next.cliOutput).not.toContain('WorkerError')
} finally {
await next.destroy()
}
})
it('should recommend the latest TypeScript package in CI when using the TypeScript CLI backend', async () => {
const next = await createNext({
files: {
'next.config.js': `
module.exports = {
experimental: { useTypeScriptCli: true },
}
`,
'pages/index.tsx': `
export default function Page() {
return <p>hello world</p>
}
`,
},
env: {
CI: '1',
},
skipStart: true,
dependencies: {
typescript: undefined,
},
})
try {
let error
await next.start().catch((err) => {
error = err
})
expect(error).toBeDefined()
expect(next.cliOutput).toContain('pnpm install --save-dev typescript')
expect(next.cliOutput).not.toContain('typescript@^6.0.0')
expect(next.cliOutput).not.toContain('Call retries were exceeded') expect(next.cliOutput).not.toContain('Call retries were exceeded')
expect(next.cliOutput).not.toContain('WorkerError') expect(next.cliOutput).not.toContain('WorkerError')
} finally { } finally {
......
...@@ -340,8 +340,11 @@ async function readNormalizedNFT(next, name) { ...@@ -340,8 +340,11 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/lib/typescript/diagnosticFormatter.js", "/node_modules/next/dist/lib/typescript/diagnosticFormatter.js",
"/node_modules/next/dist/lib/typescript/getTypeScriptConfiguration.js", "/node_modules/next/dist/lib/typescript/getTypeScriptConfiguration.js",
"/node_modules/next/dist/lib/typescript/getTypeScriptIntent.js", "/node_modules/next/dist/lib/typescript/getTypeScriptIntent.js",
"/node_modules/next/dist/lib/typescript/loadTsConfig.js",
"/node_modules/next/dist/lib/typescript/missingDependencyError.js", "/node_modules/next/dist/lib/typescript/missingDependencyError.js",
"/node_modules/next/dist/lib/typescript/runTypeCheck.js", "/node_modules/next/dist/lib/typescript/runTypeCheck.js",
"/node_modules/next/dist/lib/typescript/runTypeCheckCli.js",
"/node_modules/next/dist/lib/typescript/runTypeScriptCli.js",
"/node_modules/next/dist/lib/typescript/type-paths.js", "/node_modules/next/dist/lib/typescript/type-paths.js",
"/node_modules/next/dist/lib/typescript/writeAppTypeDeclarations.js", "/node_modules/next/dist/lib/typescript/writeAppTypeDeclarations.js",
"/node_modules/next/dist/lib/typescript/writeConfigurationDefaults.js", "/node_modules/next/dist/lib/typescript/writeConfigurationDefaults.js",
......
{
"compilerOptions": {
"baseUrl": "${configDir}/base"
}
}
{
"compilerOptions": {
"paths": {
"@wrong/*": ["source/*"]
}
}
}
{
"name": "@fixture/default-tsconfig",
"version": "1.0.0",
"main": "nested/main.json"
}
{
"compilerOptions": {
"paths": {
"@default/*": ["source/*"]
}
}
}
{
"compilerOptions": {
"paths": {
"@fixture/*": ["source/*"]
}
}
}
{
"name": "@fixture/tsconfig",
"version": "1.0.0",
"main": "index.js",
"tsconfig": "configs/base.json"
}
{
"name": "typescript",
"version": "7.0.0-test",
"type": "module",
"bin": {
"tsc": "./bin/tsc"
}
}
import { cpSync, mkdtempSync, mkdirSync, realpathSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { loadTsConfigOptions } from 'next/dist/lib/typescript/loadTsConfig'
import { getTypeScriptPackageInfo } from 'next/dist/lib/typescript/runTypeScriptCli'
describe('TypeScript CLI config metadata', () => {
let testDir: string
beforeEach(() => {
testDir = mkdtempSync(path.join(tmpdir(), 'next-tsconfig-origin-'))
cpSync(path.join(__dirname, 'fixture/project'), testDir, {
recursive: true,
})
const packageDir = path.join(testDir, 'node_modules/@fixture/tsconfig')
mkdirSync(path.dirname(packageDir), { recursive: true })
cpSync(path.join(__dirname, 'fixture/tsconfig-package'), packageDir, {
recursive: true,
})
cpSync(
path.join(__dirname, 'fixture/default-tsconfig-package'),
path.join(testDir, 'node_modules/@fixture/default-tsconfig'),
{ recursive: true }
)
cpSync(
path.join(__dirname, 'fixture/typescript-esm-package'),
path.join(testDir, 'node_modules/typescript'),
{ recursive: true }
)
})
afterEach(() => {
rmSync(testDir, { force: true, recursive: true })
})
it('uses the config selected by a package.json tsconfig field', () => {
const options = loadTsConfigOptions(path.join(testDir, 'tsconfig.json'))
expect(Array.from(options.paths?.['@fixture/*'] ?? [])).toEqual([
'source/*',
])
expect(options.pathsBasePath?.split(path.sep).slice(-4)).toEqual([
'node_modules',
'@fixture',
'tsconfig',
'configs',
])
expect(options.baseUrl).toBeUndefined()
})
it('prefers a package tsconfig.json over its JSON main', () => {
cpSync(
path.join(__dirname, 'fixture/default-project/tsconfig.json'),
path.join(testDir, 'tsconfig.json')
)
const options = loadTsConfigOptions(path.join(testDir, 'tsconfig.json'))
expect(Array.from(options.paths?.['@default/*'] ?? [])).toEqual([
'source/*',
])
expect(options.pathsBasePath?.split(path.sep).slice(-3)).toEqual([
'node_modules',
'@fixture',
'default-tsconfig',
])
})
it('expands inherited configDir templates from the root config', () => {
const configPath = path.join(
__dirname,
'fixture/config-dir/project/tsconfig.json'
)
expect(loadTsConfigOptions(configPath).baseUrl).toBe(
path.join(path.dirname(configPath), 'base')
)
})
it('uses the JS entry behind an extensionless ESM tsc wrapper', () => {
const packageInfo = getTypeScriptPackageInfo(testDir)
expect(packageInfo).toMatchObject({
version: '7.0.0-test',
apiPath: undefined,
tscPath: realpathSync(
path.join(testDir, 'node_modules/typescript/lib/tsc.js')
),
})
})
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment