Unverified Commit cbf0cef6 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Enable TypeScript CLI by default (#96497)

## Summary

Enable the project-local TypeScript CLI checker by default during `next
build`, while preserving `experimental.useTypeScriptCli: false` as an
opt-out to the TypeScript compiler API. Update the TypeScript 7
guidance, diagnostics, tests, and documentation to match the new
default.

## Verification

- `pnpm exec jest --runTestsByPath test/unit/isolated/config.test.ts`
- Pre-commit lint-staged checks passed (Prettier and ESLint)
- Not run: `pnpm test-start-turbo
test/production/app-dir/typescript-cli/typescript-cli.test.ts` (isolated
fixture dependency installation was blocked by unavailable npm registry
access)
- Not run: `pnpm --filter=next types` (repository has pre-existing
unrelated TypeScript errors)

<!-- NEXT_JS_LLM -->
parent dcdacfd0
......@@ -4,7 +4,7 @@ description: Run the project-local TypeScript CLI for type checking during produ
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.
By default, `next build` runs the project-local `tsc` command instead of loading the TypeScript JavaScript compiler API. This supports TypeScript 6 and enables [TypeScript 7](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/) while its JavaScript API is unavailable.
Install TypeScript 7 in your project:
......@@ -24,14 +24,14 @@ yarn add -D typescript@^7
bun add -D typescript@^7
```
Then, explicitly enable the CLI checker:
The CLI checker is enabled by default. To use the TypeScript JavaScript compiler API instead, set `experimental.useTypeScriptCli` to `false`:
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
useTypeScriptCli: true,
useTypeScriptCli: false,
},
}
......@@ -42,14 +42,14 @@ export default nextConfig
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
useTypeScriptCli: true,
useTypeScriptCli: false,
},
}
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.
If you opt out while using TypeScript 7, `next build` exits because the TypeScript JavaScript compiler API is unavailable.
## Behavior
......
......@@ -13,7 +13,7 @@ To add TypeScript to an existing project, rename a file to `.ts` / `.tsx`. Run `
## 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:
[TypeScript 7](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/) does not currently provide the JavaScript compiler API. To use TypeScript 7 during `next build`, install it in your project:
```bash package="pnpm"
pnpm add -D typescript@^7
......@@ -31,32 +31,7 @@ yarn add -D typescript@^7
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.
Next.js uses the project-local `tsc` CLI by default, so no additional configuration is required. To use the JavaScript compiler API instead, set [`experimental.useTypeScriptCli`](/docs/app/api-reference/config/next-config-js/useTypeScriptCli) to `false`.
> **Good to know**:
>
......@@ -85,7 +60,7 @@ You can enable the plugin in VS Code by:
height="637"
/>
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.
Now, when editing files, the custom plugin will be enabled. By default, the project-local `tsc` CLI is used when running `next build`. Set [`experimental.useTypeScriptCli`](#using-typescript-7) to `false` to use the custom type checker instead.
The TypeScript plugin can help with:
......
......@@ -1463,5 +1463,7 @@
"1462": "Unexpected chunk emitted in Before stage",
"1463": "\\`experimental.turbopackGenerateComponentChunks\\` has been moved to \\`experimental.turbopackChunking.generateComponentChunks\\`. Please update your next.config.js file accordingly.",
"1464": "\\`experimental.turbopackChunkingHeuristics\\` has been renamed to \\`experimental.turbopackChunking\\`. Please update your next.config.js file accordingly.",
"1465": "\\`experimental.useCache\\` cannot be disabled when \\`cacheComponents\\` is enabled, because Cache Components relies on the \\`\"use cache\"\\` directive. Please remove it from %s."
"1465": "\\`experimental.useCache\\` cannot be disabled when \\`cacheComponents\\` is enabled, because Cache Components relies on the \\`\"use cache\"\\` directive. Please remove it from %s.",
"1466": "TypeScript %s does not provide the compiler API required by Next.js. Set %s to true in your Next.js config to use the TypeScript CLI, or install TypeScript 6 instead.",
"1467": "TypeScript %s does not provide the compiler API required by Next.js. Set %s back to true in your Next.js config to use the TypeScript CLI, or install TypeScript 6 instead."
}
......@@ -73,7 +73,7 @@ export function hasNativeTypeScriptPreview(baseDir: string): boolean {
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, ` +
`Set ${bold('experimental.useTypeScriptCli')} back to true in your Next.js config to use the TypeScript CLI, ` +
`or install TypeScript 6 instead.`
)
}
......
......@@ -2223,7 +2223,7 @@ export const defaultConfig = Object.freeze({
webpackMemoryOptimizations: false,
optimizeServerReact: true,
strictRouteTypes: false,
useTypeScriptCli: false,
useTypeScriptCli: true,
removeUncaughtErrorAndRejectionListeners: false,
validateRSCRequestHeaders: true,
staleTimes: {
......
......@@ -5,6 +5,9 @@ import { check } from 'next-test-utils'
describe('Legacy decorators SWC option', () => {
describe('with extended tsconfig', () => {
const { next } = nextTestSetup({
nextConfig: {
experimental: { useTypeScriptCli: false },
},
files: {
'tsconfig.json': new FileRef(
join(__dirname, 'legacy-decorators/tsconfig-extended.json')
......
......@@ -4,6 +4,11 @@ import { retry } from 'next-test-utils'
describe('stale-dev-types', () => {
const { next } = nextTestSetup({
files: __dirname,
nextConfig: {
experimental: {
useTypeScriptCli: false,
},
},
})
it('should not fail build when .next/dev has stale types from deleted routes', async () => {
......
......@@ -3,6 +3,11 @@ import { retry } from 'next-test-utils'
describe('typescript-native-preview', () => {
const { next } = nextTestSetup({
nextConfig: {
experimental: {
useTypeScriptCli: false,
},
},
files: {
'app/layout.tsx': `
import { ReactNode } from 'react'
......
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
const nextConfig = {
experimental: {
useTypeScriptCli: false,
},
}
module.exports = nextConfig
......@@ -6,6 +6,9 @@ setInterval(() => {}, 250)
*/
const nextConfig = {
typedRoutes: true,
experimental: {
useTypeScriptCli: false,
},
async redirects() {
return [
{
......
......@@ -20,6 +20,7 @@ import cheerio from 'cheerio'
import { once } from 'events'
import type { Playwright } from '../browsers/playwright'
import escapeStringRegexp from 'escape-string-regexp'
import * as JSON5 from 'json5'
import { Page, Response } from 'playwright'
type Event = 'stdout' | 'stderr' | 'error' | 'destroy'
......@@ -448,10 +449,24 @@ export class NextInstance {
require('console').log(
'tsconfig.test.json found, using it for this test'
)
await fs.copyFile(
path.join(this.testDir, 'tsconfig.test.json'),
path.join(this.testDir, 'tsconfig.json')
)
const tsConfigTestPath = path.join(this.testDir, 'tsconfig.test.json')
const tsConfigPath = path.join(this.testDir, 'tsconfig.json')
if (this.env.NEXT_PRIVATE_LOCAL_DEV) {
const tsConfig = JSON5.parse(
await fs.readFile(tsConfigTestPath, 'utf8')
)
const exclude = new Set<string>(tsConfig.exclude ?? [])
exclude.add('**/*.test.ts')
exclude.add('**/*.test.tsx')
tsConfig.exclude = Array.from(exclude)
await fs.writeFile(
tsConfigPath,
JSON.stringify(tsConfig, null, 2) + os.EOL
)
} else {
await fs.copyFile(tsConfigTestPath, tsConfigPath)
}
}
if (isNextDeploy) {
......
......@@ -7,6 +7,7 @@ import stripAnsi from 'strip-ansi'
import { quote as shellQuote } from 'shell-quote'
import { shouldUseTurbopack } from 'next-test-utils'
import { RequiredServerFilesManifest } from 'next/dist/build'
import { FileRef } from '../e2e-utils'
export class NextStartInstance extends NextInstance {
private _buildId: string
......@@ -24,6 +25,15 @@ export class NextStartInstance extends NextInstance {
constructor(opts: NextInstanceOpts) {
super(opts)
if (typeof opts.files === 'string' || opts.files instanceof FileRef) {
// Directory fixtures can include their test runner. Keep it in the
// generated app while excluding it from TypeScript checks.
this.env = {
NEXT_PRIVATE_LOCAL_DEV: '1',
...this.env,
}
}
if (!opts.disableAutoSkewProtection && shouldUseTurbopack()) {
this.env.NEXT_DEPLOYMENT_ID = 'test-dpl-id-1234'
this.env.__NEXT_SUPPORTS_IMMUTABLE_ASSETS = '1'
......
......@@ -2,6 +2,7 @@
module.exports = {
typedRoutes: true,
experimental: {
useTypeScriptCli: false,
webpackBuildWorker: true,
},
}
......@@ -3,6 +3,7 @@ module.exports = {
typedRoutes: true,
experimental: {
parallelServerBuildTraces: true,
useTypeScriptCli: false,
webpackBuildWorker: true,
},
}
......@@ -2,9 +2,6 @@
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
useTypeScriptCli: true,
},
typescript: {
tsconfigPath: 'tsconfig.build.json',
},
......
import { nextTestSetup } from 'e2e-utils'
const cliConfig = `module.exports = {
experimental: { useTypeScriptCli: true },
const defaultConfig = `module.exports = {
typescript: { tsconfigPath: 'tsconfig.build.json' },
}
`
const apiConfig = `module.exports = {
experimental: { useTypeScriptCli: false },
typescript: { tsconfigPath: 'tsconfig.build.json' },
}
`
......@@ -14,7 +14,7 @@ const apiConfig = `module.exports = {
const typeError = `export const invalidValue: number = 'not a number'
`
describe('experimental TypeScript CLI backend', () => {
describe('TypeScript CLI backend', () => {
describe('TypeScript 7', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
......@@ -34,7 +34,7 @@ describe('experimental TypeScript CLI backend', () => {
})
afterEach(async () => {
await next.patchFile('next.config.js', cliConfig)
await next.patchFile('next.config.js', defaultConfig)
await next.patchFile('tsconfig.build.json', originalTsConfig)
await next.deleteFile('src/type-error.ts').catch(() => {})
await next
......@@ -53,6 +53,7 @@ describe('experimental TypeScript CLI backend', () => {
expect(result.cliOutput).toContain('"typeCheckMode": "typescript-cli"')
expect(result.cliOutput).not.toContain('"inputFilesCount"')
expect(result.cliOutput).not.toContain('"totalFilesCount"')
expect(await next.hasFile('typescript-cli.test.ts')).toBe(true)
expect(await next.hasFile('.next/cache/.tsbuildinfo')).toBe(true)
})
......@@ -86,7 +87,6 @@ describe('experimental TypeScript CLI backend', () => {
await next.patchFile(
'next.config.js',
`module.exports = {
experimental: { useTypeScriptCli: true },
typescript: {
ignoreBuildErrors: true,
tsconfigPath: 'tsconfig.build.json',
......@@ -122,7 +122,7 @@ describe('experimental TypeScript CLI backend', () => {
})
})
describe('TypeScript 7 without the opt-in', () => {
describe('TypeScript 7 with the CLI disabled', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
......@@ -134,7 +134,7 @@ describe('experimental TypeScript CLI backend', () => {
if (skipped) return
it('fails with actionable migration guidance', async () => {
it('fails with actionable API compatibility guidance', async () => {
await next.patchFile('next.config.js', apiConfig)
const result = await next.build()
......@@ -143,7 +143,9 @@ describe('experimental TypeScript CLI backend', () => {
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(
'Set experimental.useTypeScriptCli back to true'
)
expect(result.cliOutput).toContain('install TypeScript 6 instead')
})
})
......
......@@ -4,6 +4,9 @@ const withMdx = createMdx()
export default withMdx({
typedRoutes: true,
experimental: {
useTypeScriptCli: false,
},
pageExtensions: ['js', 'jsx', 'ts', 'tsx', 'mdx'],
......
......@@ -3,6 +3,9 @@ import { nextTestSetup } from 'e2e-utils'
describe('ci-missing-typescript-deps', () => {
describe('missing typescript dep', () => {
const { next } = nextTestSetup({
nextConfig: {
experimental: { useTypeScriptCli: false },
},
files: {
'pages/index.tsx': `
export default function Page() {
......
/** @type {import('next').NextConfig} */
const nextConfig = {}
const nextConfig = {
experimental: {
useTypeScriptCli: false,
},
}
module.exports = nextConfig
/** @type {import('next').NextConfig} */
const nextConfig = {}
const nextConfig = {
experimental: {
useTypeScriptCli: false,
},
}
module.exports = nextConfig
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
useTypeScriptCli: false,
},
}
module.exports = nextConfig
......@@ -6,6 +6,12 @@ const strictRouteTypes =
describe('tsconfig.json verifier', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
nextConfig: {
experimental: { useTypeScriptCli: false },
},
env: {
NEXT_PRIVATE_LOCAL_DEV: '',
},
skipStart: true,
skipDeployment: true,
})
......@@ -1130,6 +1136,12 @@ describe('tsconfig.json verifier', () => {
describe('tsconfig.json verifier 5.x', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
nextConfig: {
experimental: { useTypeScriptCli: false },
},
env: {
NEXT_PRIVATE_LOCAL_DEV: '',
},
skipStart: true,
dependencies: {
typescript: '5.9.3',
......
......@@ -21,6 +21,7 @@ describe('TypeScript with error handling options', () => {
.catch(() => '')
originalTsConfig = await next.readFile('tsconfig.json')
const nextConfig = {
experimental: { useTypeScriptCli: false },
typescript: { ignoreBuildErrors },
}
await next.patchFile(
......
......@@ -62,6 +62,28 @@ describe('config', () => {
expect(config.onDemandEntries.maxInactiveAge).toBeDefined()
})
it('Should enable the TypeScript CLI by default and allow opting out', async () => {
const defaultConfig = await loadConfig(
PHASE_DEVELOPMENT_SERVER,
'<rootDir>-typescript-cli-default',
{ customConfig: {} }
)
expect(defaultConfig.experimental.useTypeScriptCli).toBe(true)
const apiConfig = await loadConfig(
PHASE_DEVELOPMENT_SERVER,
'<rootDir>-typescript-api',
{
customConfig: {
experimental: {
useTypeScriptCli: false,
},
},
}
)
expect(apiConfig.experimental.useTypeScriptCli).toBe(false)
})
it('Should configure the development memory threshold opt-out', async () => {
const defaultConfig = await loadConfig(
PHASE_DEVELOPMENT_SERVER,
......
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