Unverified Commit 3275034b authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

Allow `next.config.mts` for Node.js native TS resolver (#83556)

Following up on https://github.com/vercel/next.js/pull/83240

When using ESM syntax in `next.config.ts` on a CJS project, Node.js
first assumes it as CJS, then parses it into ESM again, giving a
warning:

```
(node:27529) [MODULE_TYPELESS_PACKAGE_JSON] Warning: Module type of file://.../next.config.ts is not specified and it doesn't parse as CommonJS.
Reparsing as ES module because module syntax was detected. This incurs a performance overhead.
To eliminate this warning, add "type": "module" to .../package.json.
```

Therefore, give users the option to use `next.config.mts` which Node.js
expects ESM syntax.

The tests are a copy of `next-config-ts-native-ts` and only renamed the
config to mts.

---------
Co-authored-by: 's avatarSebastian "Sebbie" Silbermann <sebastian.silbermann@vercel.com>
parent fd9f0d14
...@@ -66,7 +66,7 @@ ...@@ -66,7 +66,7 @@
"plugin:@typescript-eslint/recommended", "plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/stylistic" "plugin:@typescript-eslint/stylistic"
], ],
"files": ["**/*.ts", "**/*.tsx"], "files": ["**/*.ts", "**/*.tsx", "**/*.mts"],
"parser": "@typescript-eslint/parser", "parser": "@typescript-eslint/parser",
"parserOptions": { "parserOptions": {
"sourceType": "module", "sourceType": "module",
......
...@@ -561,9 +561,7 @@ jobs: ...@@ -561,9 +561,7 @@ jobs:
with: with:
nodeVersion: ${{ matrix.node }} nodeVersion: ${{ matrix.node }}
afterBuild: | afterBuild: |
export NEXT_TEST_MODE=dev NEXT_TEST_MODE=dev NODE_OPTIONS=--experimental-transform-types node run-tests.js test/e2e/app-dir/next-config-ts-native-ts/**/*.test.ts test/e2e/app-dir/next-config-ts-native-mts/**/*.test.ts
export NODE_OPTIONS=--experimental-transform-types
node run-tests.js test/e2e/app-dir/next-config-ts-native-ts/**/*.test.ts
stepName: 'test-next-config-ts-native-ts-dev-${{ matrix.node }}' stepName: 'test-next-config-ts-native-ts-dev-${{ matrix.node }}'
secrets: inherit secrets: inherit
...@@ -583,9 +581,7 @@ jobs: ...@@ -583,9 +581,7 @@ jobs:
with: with:
nodeVersion: ${{ matrix.node }} nodeVersion: ${{ matrix.node }}
afterBuild: | afterBuild: |
export NEXT_TEST_MODE=start NEXT_TEST_MODE=start NODE_OPTIONS=--experimental-transform-types node run-tests.js test/e2e/app-dir/next-config-ts-native-ts/**/*.test.ts test/e2e/app-dir/next-config-ts-native-mts/**/*.test.ts
export NODE_OPTIONS=--experimental-transform-types
node run-tests.js test/e2e/app-dir/next-config-ts-native-ts/**/*.test.ts
stepName: 'test-next-config-ts-native-ts-prod-${{ matrix.node }}' stepName: 'test-next-config-ts-native-ts-prod-${{ matrix.node }}'
secrets: inherit secrets: inherit
......
...@@ -22,6 +22,12 @@ ...@@ -22,6 +22,12 @@
"@/*": ["./*"] "@/*": ["./*"]
} }
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"] "exclude": ["node_modules"]
} }
...@@ -22,6 +22,12 @@ ...@@ -22,6 +22,12 @@
"@/*": ["./*"] "@/*": ["./*"]
} }
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"] "exclude": ["node_modules"]
} }
...@@ -22,6 +22,12 @@ ...@@ -22,6 +22,12 @@
"@/*": ["./*"] "@/*": ["./*"]
} }
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"] "exclude": ["node_modules"]
} }
...@@ -22,6 +22,12 @@ ...@@ -22,6 +22,12 @@
"@/*": ["./*"] "@/*": ["./*"]
} }
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"] "exclude": ["node_modules"]
} }
...@@ -22,6 +22,12 @@ ...@@ -22,6 +22,12 @@
"@/*": ["./*"] "@/*": ["./*"]
} }
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"] "exclude": ["node_modules"]
} }
...@@ -17,6 +17,12 @@ ...@@ -17,6 +17,12 @@
"@/*": ["./*"] "@/*": ["./*"]
} }
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"] "exclude": ["node_modules"]
} }
...@@ -17,6 +17,12 @@ ...@@ -17,6 +17,12 @@
"@/*": ["./*"] "@/*": ["./*"]
} }
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"] "exclude": ["node_modules"]
} }
...@@ -17,6 +17,12 @@ ...@@ -17,6 +17,12 @@
"@/*": ["./*"] "@/*": ["./*"]
} }
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"] "exclude": ["node_modules"]
} }
...@@ -17,6 +17,12 @@ ...@@ -17,6 +17,12 @@
"@/*": ["./*"] "@/*": ["./*"]
} }
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"] "exclude": ["node_modules"]
} }
...@@ -122,6 +122,7 @@ export async function transpileConfig({ ...@@ -122,6 +122,7 @@ export async function transpileConfig({
// Node.js v22.10.0+ // Node.js v22.10.0+
// Value is 'strip' or 'transform' based on how the feature is enabled. // Value is 'strip' or 'transform' based on how the feature is enabled.
// https://nodejs.org/api/process.html#processfeaturestypescript // https://nodejs.org/api/process.html#processfeaturestypescript
// TODO: Remove `as any` once we bump @types/node to v22.10.0+
if ((process.features as any).typescript) { if ((process.features as any).typescript) {
// Run import() here to catch errors and fallback to legacy resolution. // Run import() here to catch errors and fallback to legacy resolution.
return (await import(pathToFileURL(nextConfigPath).href)).default return (await import(pathToFileURL(nextConfigPath).href)).default
......
...@@ -3,6 +3,8 @@ import { tmpdir } from 'node:os' ...@@ -3,6 +3,8 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path' import { join } from 'node:path'
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
import ts from 'typescript' import ts from 'typescript'
// eslint-disable-next-line import/no-extraneous-dependencies
import stripAnsi from 'strip-ansi'
import { writeConfigurationDefaults } from './writeConfigurationDefaults' import { writeConfigurationDefaults } from './writeConfigurationDefaults'
describe('writeConfigurationDefaults()', () => { describe('writeConfigurationDefaults()', () => {
...@@ -46,53 +48,51 @@ describe('writeConfigurationDefaults()', () => { ...@@ -46,53 +48,51 @@ describe('writeConfigurationDefaults()', () => {
hasPagesDir hasPagesDir
) )
const tsConfig = await readFile(tsConfigPath, { encoding: 'utf8' }) const tsConfig = JSON.parse(
await readFile(tsConfigPath, { encoding: 'utf8' })
expect(JSON.parse(tsConfig)).toMatchInlineSnapshot(` )
{
"compilerOptions": { expect(tsConfig).toMatchInlineSnapshot(`
"allowJs": true, {
"esModuleInterop": true, "compilerOptions": {
"incremental": true, "allowJs": true,
"isolatedModules": true, "esModuleInterop": true,
"jsx": "react-jsx", "incremental": true,
"lib": [ "isolatedModules": true,
"dom", "jsx": "react-jsx",
"dom.iterable", "lib": [
"esnext", "dom",
], "dom.iterable",
"module": "esnext", "esnext",
"moduleResolution": "node", ],
"noEmit": true, "module": "esnext",
"plugins": [ "moduleResolution": "node",
{ "noEmit": true,
"name": "next", "plugins": [
}, {
], "name": "next",
"resolveJsonModule": true, },
"skipLibCheck": true, ],
"strict": false, "resolveJsonModule": true,
"target": "ES2017", "skipLibCheck": true,
}, "strict": false,
"exclude": [ "target": "ES2017",
"node_modules", },
], "exclude": [
"include": [ "node_modules",
"next-env.d.ts", ],
".next/types/**/*.ts", "include": [
"**/*.ts", "next-env.d.ts",
"**/*.tsx", ".next/types/**/*.ts",
], "**/*.mts",
} "**/*.ts",
`) "**/*.tsx",
],
expect( }
consoleLogSpy.mock.calls `)
.flat()
.join('\n') expect(stripAnsi(consoleLogSpy.mock.calls.flat().join('\n')))
// eslint-disable-next-line no-control-regex .toMatchInlineSnapshot(`
.replace(/\x1B\[\d+m/g, '') // remove color control characters
).toMatchInlineSnapshot(`
" "
We detected TypeScript in your project and reconfigured your tsconfig.json file for you. Strict-mode is set to false by default. We detected TypeScript in your project and reconfigured your tsconfig.json file for you. Strict-mode is set to false by default.
The following suggested values were added to your tsconfig.json. These values can be changed to fit your project's needs: The following suggested values were added to your tsconfig.json. These values can be changed to fit your project's needs:
...@@ -104,7 +104,7 @@ describe('writeConfigurationDefaults()', () => { ...@@ -104,7 +104,7 @@ describe('writeConfigurationDefaults()', () => {
- strict was set to false - strict was set to false
- noEmit was set to true - noEmit was set to true
- incremental was set to true - incremental was set to true
- include was set to ['next-env.d.ts', '.next/types/**/*.ts', '**/*.ts', '**/*.tsx'] - include was set to ['next-env.d.ts', '.next/types/**/*.ts', '**/*.mts', '**/*.ts', '**/*.tsx']
- plugins was updated to add { name: 'next' } - plugins was updated to add { name: 'next' }
- exclude was set to ['node_modules'] - exclude was set to ['node_modules']
...@@ -136,13 +136,9 @@ describe('writeConfigurationDefaults()', () => { ...@@ -136,13 +136,9 @@ describe('writeConfigurationDefaults()', () => {
hasPagesDir hasPagesDir
) )
expect( expect(stripAnsi(consoleLogSpy.mock.calls.flat().join('\n'))).not.toMatch(
consoleLogSpy.mock.calls 'Strict-mode is set to false by default.'
.flat() )
.join('\n')
// eslint-disable-next-line no-control-regex
.replace(/\x1B\[\d+m/g, '') // remove color control characters
).not.toMatch('Strict-mode is set to false by default.')
}) })
describe('with tsconfig extends', () => { describe('with tsconfig extends', () => {
...@@ -155,7 +151,7 @@ describe('writeConfigurationDefaults()', () => { ...@@ -155,7 +151,7 @@ describe('writeConfigurationDefaults()', () => {
}) })
it('should support empty includes when base provides it', async () => { it('should support empty includes when base provides it', async () => {
const include = ['**/*.ts', '**/*.tsx', nextAppTypes] const include = ['**/*.ts', '**/*.tsx', nextAppTypes, '**/*.mts']
const content = { extends: './tsconfig.base.json' } const content = { extends: './tsconfig.base.json' }
const baseContent = { include } const baseContent = { include }
...@@ -202,11 +198,12 @@ describe('writeConfigurationDefaults()', () => { ...@@ -202,11 +198,12 @@ describe('writeConfigurationDefaults()', () => {
const parsed = JSON.parse(output) const parsed = JSON.parse(output)
expect(parsed.include.sort()).toMatchInlineSnapshot(` expect(parsed.include.sort()).toMatchInlineSnapshot(`
[ [
"**/*.ts", "**/*.mts",
"**/*.tsx", "**/*.ts",
".next/types/**/*.ts", "**/*.tsx",
] ".next/types/**/*.ts",
]
`) `)
}) })
......
...@@ -212,44 +212,56 @@ export async function writeConfigurationDefaults( ...@@ -212,44 +212,56 @@ export async function writeConfigurationDefaults(
if (!('include' in rawConfig)) { if (!('include' in rawConfig)) {
userTsConfig.include = hasAppDir userTsConfig.include = hasAppDir
? ['next-env.d.ts', nextAppTypes, '**/*.ts', '**/*.tsx'] ? ['next-env.d.ts', nextAppTypes, '**/*.mts', '**/*.ts', '**/*.tsx']
: ['next-env.d.ts', '**/*.ts', '**/*.tsx'] : ['next-env.d.ts', '**/*.mts', '**/*.ts', '**/*.tsx']
suggestedActions.push( suggestedActions.push(
cyan('include') + cyan('include') +
' was set to ' + ' was set to ' +
bold( bold(
hasAppDir hasAppDir
? `['next-env.d.ts', '${nextAppTypes}', '**/*.ts', '**/*.tsx']` ? `['next-env.d.ts', '${nextAppTypes}', '**/*.mts', '**/*.ts', '**/*.tsx']`
: `['next-env.d.ts', '**/*.ts', '**/*.tsx']` : `['next-env.d.ts', '**/*.mts', '**/*.ts', '**/*.tsx']`
) )
) )
} else if (hasAppDir && !rawConfig.include.includes(nextAppTypes)) { } else if (hasAppDir) {
if (!Array.isArray(userTsConfig.include)) { const missingFromResolved = []
userTsConfig.include = [] if (!rawConfig.include.includes(nextAppTypes)) {
missingFromResolved.push(nextAppTypes)
} }
// rawConfig will resolve all extends and include paths (ex: tsconfig.json, tsconfig.base.json, etc.) if (!rawConfig.include.includes('**/*.mts')) {
// if it doesn't match userTsConfig then update the userTsConfig to add the missingFromResolved.push('**/*.mts')
// rawConfig's includes in addition to nextAppTypes }
if (
rawConfig.include.length !== userTsConfig.include.length || if (missingFromResolved.length > 0) {
JSON.stringify(rawConfig.include.sort()) !== if (!Array.isArray(userTsConfig.include)) {
JSON.stringify(userTsConfig.include.sort()) userTsConfig.include = []
) { }
userTsConfig.include.push(...rawConfig.include, nextAppTypes) // rawConfig will resolve all extends and include paths (ex: tsconfig.json, tsconfig.base.json, etc.)
suggestedActions.push( // if it doesn't match userTsConfig then update the userTsConfig to add the
cyan('include') + // rawConfig's includes in addition to missing items
' was set to ' + if (
bold( rawConfig.include.length !== userTsConfig.include.length ||
`[${[...rawConfig.include, nextAppTypes] JSON.stringify(rawConfig.include.sort()) !==
.map((i) => `'${i}'`) JSON.stringify(userTsConfig.include.sort())
.join(', ')}]` ) {
userTsConfig.include.push(...rawConfig.include, ...missingFromResolved)
suggestedActions.push(
cyan('include') +
' was set to ' +
bold(
`[${[...rawConfig.include, ...missingFromResolved]
.map((i) => `'${i}'`)
.join(', ')}]`
)
)
} else {
missingFromResolved.forEach((item) => {
userTsConfig.include.push(item)
suggestedActions.push(
cyan('include') + ' was updated to add ' + bold(`'${item}'`)
) )
) })
} else { }
userTsConfig.include.push(nextAppTypes)
suggestedActions.push(
cyan('include') + ' was updated to add ' + bold(`'${nextAppTypes}'`)
)
} }
} }
......
...@@ -1592,7 +1592,8 @@ export default async function loadConfig( ...@@ -1592,7 +1592,8 @@ export default async function loadConfig(
[ [
`${configBaseName}.cjs`, `${configBaseName}.cjs`,
`${configBaseName}.cts`, `${configBaseName}.cts`,
`${configBaseName}.mts`, // TODO: Remove `as any` once we bump @types/node to v22.10.0+
...((process.features as any).typescript ? [] : ['next.config.mts']),
`${configBaseName}.json`, `${configBaseName}.json`,
`${configBaseName}.jsx`, `${configBaseName}.jsx`,
`${configBaseName}.tsx`, `${configBaseName}.tsx`,
......
...@@ -109,6 +109,9 @@ export const CONFIG_FILES = [ ...@@ -109,6 +109,9 @@ export const CONFIG_FILES = [
'next.config.js', 'next.config.js',
'next.config.mjs', 'next.config.mjs',
'next.config.ts', 'next.config.ts',
// process.features can be undefined on Edge runtime
// TODO: Remove `as any` once we bump @types/node to v22.10.0+
...((process?.features as any)?.typescript ? ['next.config.mts'] : []),
] ]
export const BUILD_ID_FILE = 'BUILD_ID' export const BUILD_ID_FILE = 'BUILD_ID'
export const BLOCKED_PAGES = ['/_document', '/_app', '/_error'] export const BLOCKED_PAGES = ['/_document', '/_app', '/_error']
......
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>{process.env.foo}</p>
}
import { nextTestSetup } from 'e2e-utils'
describe('next-config-ts-async-function-cjs', () => {
// TODO: Remove this once we bump minimum Node.js version to v22
if (!(process.features as any).typescript) {
it.skip('requires `process.features.typescript` to feature detect Node.js native TS', () => {})
return
}
const { next } = nextTestSetup({
files: __dirname,
})
it('should support config as async function (CJS)', async () => {
const $ = await next.render$('/')
expect($('p').text()).toBe('foo')
})
})
import { nextTestSetup } from 'e2e-utils'
describe('next-config-ts-async-function-esm', () => {
// TODO: Remove this once we bump minimum Node.js version to v22
if (!(process.features as any).typescript) {
it.skip('requires `process.features.typescript` to feature detect Node.js native TS', () => {})
return
}
const { next } = nextTestSetup({
files: __dirname,
packageJson: {
type: 'module',
},
})
it('should support config as async function (ESM)', async () => {
const $ = await next.render$('/')
expect($('p').text()).toBe('foo')
})
})
import type { NextConfig } from 'next'
// top-level await will only work in Native TS mode.
// This is to ensure that the test is running in Native TS mode.
await Promise.resolve()
const nextConfigAsyncFunction = async (phase, { defaultConfig }) => {
const nextConfig: NextConfig = {
...defaultConfig,
env: {
foo: phase ? 'foo' : 'bar',
},
}
return nextConfig
}
export default nextConfigAsyncFunction
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>{process.env.foo}</p>
}
import { nextTestSetup } from 'e2e-utils'
describe('next-config-ts-dynamic-import-esm', () => {
// TODO: Remove this once we bump minimum Node.js version to v22
if (!(process.features as any).typescript) {
it.skip('requires `process.features.typescript` to feature detect Node.js native TS', () => {})
return
}
const { next } = nextTestSetup({
files: __dirname,
packageJson: {
type: 'module',
},
})
it('should support dynamic import (ESM)', async () => {
const $ = await next.render$('/')
expect($('p').text()).toBe('foo')
})
})
import type { NextConfig } from 'next'
// top-level await will only work in Native TS mode.
// This is to ensure that the test is running in Native TS mode.
await Promise.resolve()
const nextConfig = async () => {
const { foo } = await import('./foo.ts')
const nextConfig: NextConfig = {
env: {
foo,
},
}
return nextConfig
}
export default nextConfig
{
"compilerOptions": {
"allowImportingTsExtensions": true
}
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>{process.env.foo}</p>
}
import { nextTestSetup } from 'e2e-utils'
describe('next-config-ts-export-as-default-cjs', () => {
// TODO: Remove this once we bump minimum Node.js version to v22
if (!(process.features as any).typescript) {
it.skip('requires `process.features.typescript` to feature detect Node.js native TS', () => {})
return
}
const { next } = nextTestSetup({
files: __dirname,
})
it('should support export as default (CJS)', async () => {
const $ = await next.render$('/')
expect($('p').text()).toBe('foo')
})
})
import { nextTestSetup } from 'e2e-utils'
describe('next-config-ts-export-as-default-esm', () => {
// TODO: Remove this once we bump minimum Node.js version to v22
if (!(process.features as any).typescript) {
it.skip('requires `process.features.typescript` to feature detect Node.js native TS', () => {})
return
}
const { next } = nextTestSetup({
files: __dirname,
packageJson: {
type: 'module',
},
})
it('should support export as default (ESM)', async () => {
const $ = await next.render$('/')
expect($('p').text()).toBe('foo')
})
})
import type { NextConfig } from 'next'
// top-level await will only work in Native TS mode.
// This is to ensure that the test is running in Native TS mode.
await Promise.resolve()
const nextConfig: NextConfig = {
env: {
foo: 'foo',
},
}
export { nextConfig as default }
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>{process.env.foo}</p>
}
import { nextTestSetup } from 'e2e-utils'
describe('next-config-ts-export-default-cjs', () => {
// TODO: Remove this once we bump minimum Node.js version to v22
if (!(process.features as any).typescript) {
it.skip('requires `process.features.typescript` to feature detect Node.js native TS', () => {})
return
}
const { next } = nextTestSetup({
files: __dirname,
})
it('should support export default (CJS)', async () => {
const $ = await next.render$('/')
expect($('p').text()).toBe('foo')
})
})
import { nextTestSetup } from 'e2e-utils'
describe('next-config-ts-export-default-esm', () => {
// TODO: Remove this once we bump minimum Node.js version to v22
if (!(process.features as any).typescript) {
it.skip('requires `process.features.typescript` to feature detect Node.js native TS', () => {})
return
}
const { next } = nextTestSetup({
files: __dirname,
packageJson: {
type: 'module',
},
})
it('should support export default (ESM)', async () => {
const $ = await next.render$('/')
expect($('p').text()).toBe('foo')
})
})
import type { NextConfig } from 'next'
// top-level await will only work in Native TS mode.
// This is to ensure that the test is running in Native TS mode.
await Promise.resolve()
export default {
env: {
foo: 'foo',
},
} satisfies NextConfig
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return (
<p>
{JSON.stringify([
process.env.cjs,
process.env.mjs,
process.env.jsCJS,
process.env.jsESM,
])}
</p>
)
}
import { nextTestSetup } from 'e2e-utils'
describe('next-config-ts-import-from-node-modules-cjs', () => {
// TODO: Remove this once we bump minimum Node.js version to v22
if (!(process.features as any).typescript) {
it.skip('requires `process.features.typescript` to feature detect Node.js native TS', () => {})
return
}
const { next } = nextTestSetup({
files: __dirname,
})
it('should import from node_modules (CJS)', async () => {
const $ = await next.render$('/')
const text = $('p').text()
expect(text).toContain('cjs')
expect(text).toContain('mjs')
expect(text).toContain('jsCJS')
expect(text).toContain('jsESM')
})
})
import { nextTestSetup } from 'e2e-utils'
describe('next-config-ts-import-from-node-modules-esm', () => {
// TODO: Remove this once we bump minimum Node.js version to v22
if (!(process.features as any).typescript) {
it.skip('requires `process.features.typescript` to feature detect Node.js native TS', () => {})
return
}
const { next } = nextTestSetup({
files: __dirname,
packageJson: {
type: 'module',
},
})
it('should import from node_modules (ESM)', async () => {
const $ = await next.render$('/')
const text = $('p').text()
expect(text).toContain('cjs')
expect(text).toContain('mjs')
expect(text).toContain('jsCJS')
expect(text).toContain('jsESM')
})
})
import type { NextConfig } from 'next'
import cjs from 'cjs'
import mjs from 'mjs'
import jsCJS from 'js-cjs'
import jsESM from 'js-esm'
// top-level await will only work in Native TS mode.
// This is to ensure that the test is running in Native TS mode.
await Promise.resolve()
const nextConfig: NextConfig = {
env: {
cjs,
mjs,
jsCJS,
jsESM,
},
}
export default nextConfig
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return (
<p>
{JSON.stringify([
process.env.js,
process.env.cjs,
process.env.mjs,
process.env.cts,
process.env.mts,
process.env.ts,
])}
</p>
)
}
import { nextTestSetup } from 'e2e-utils'
describe('next-config-ts-import-js-extensions-cjs', () => {
// TODO: Remove this once we bump minimum Node.js version to v22
if (!(process.features as any).typescript) {
it.skip('requires `process.features.typescript` to feature detect Node.js native TS', () => {})
return
}
const { next } = nextTestSetup({
files: __dirname,
})
it('should import js extensions (CJS)', async () => {
const $ = await next.render$('/')
const text = $('p').text()
expect(text).toContain('jsCJS')
expect(text).toContain('cjs')
expect(text).toContain('mjs')
expect(text).toContain('cts')
expect(text).toContain('mts')
expect(text).toContain('ts')
})
})
import type { NextConfig } from 'next'
import cjs from './fixtures/cjs.cjs'
import mjs from './fixtures/mjs.mjs'
import * as cts from './fixtures/cts.cts'
import mts from './fixtures/mts.mts'
import ts from './fixtures/ts.ts'
import js from './fixtures/js-cjs.js'
// top-level await will only work in Native TS mode.
// This is to ensure that the test is running in Native TS mode.
await Promise.resolve()
const nextConfig: NextConfig = {
env: {
cjs,
mjs,
// Node.js native TS can't handle `export =` syntax.
cts: (cts as any).default,
mts,
ts,
js,
},
}
export default nextConfig
{
"compilerOptions": {
"allowImportingTsExtensions": true,
"esModuleInterop": true,
"allowJs": true
}
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return (
<p>
{JSON.stringify([
process.env.js,
process.env.cjs,
process.env.mjs,
process.env.cts,
process.env.mts,
process.env.ts,
])}
</p>
)
}
import { nextTestSetup } from 'e2e-utils'
describe('next-config-ts-import-js-extensions-esm', () => {
// TODO: Remove this once we bump minimum Node.js version to v22
if (!(process.features as any).typescript) {
it.skip('requires `process.features.typescript` to feature detect Node.js native TS', () => {})
return
}
const { next } = nextTestSetup({
files: __dirname,
packageJson: {
type: 'module',
},
})
it('should import js extensions (ESM)', async () => {
const $ = await next.render$('/')
const text = $('p').text()
expect(text).toContain('jsESM')
expect(text).toContain('cjs')
expect(text).toContain('mjs')
expect(text).toContain('cts')
expect(text).toContain('mts')
expect(text).toContain('ts')
})
})
import type { NextConfig } from 'next'
import cjs from './fixtures/cjs.cjs'
import mjs from './fixtures/mjs.mjs'
import * as cts from './fixtures/cts.cts'
import mts from './fixtures/mts.mts'
import ts from './fixtures/ts.ts'
import js from './fixtures/js-esm.js'
// top-level await will only work in Native TS mode.
// This is to ensure that the test is running in Native TS mode.
await Promise.resolve()
const nextConfig: NextConfig = {
env: {
cjs,
mjs,
// Node.js native TS can't handle `export =` syntax.
cts: (cts as any).default,
mts,
ts,
js,
},
}
export default nextConfig
{
"compilerOptions": {
"allowImportingTsExtensions": true,
"esModuleInterop": true,
"allowJs": true
}
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>{process.env.foo}</p>
}
import { nextTestSetup } from 'e2e-utils'
describe('next-config-ts-import-json-cjs', () => {
// TODO: Remove this once we bump minimum Node.js version to v22
if (!(process.features as any).typescript) {
it.skip('requires `process.features.typescript` to feature detect Node.js native TS', () => {})
return
}
const { next } = nextTestSetup({
files: __dirname,
})
it('should support import json (CJS)', async () => {
const $ = await next.render$('/')
expect($('p').text()).toBe('foo')
})
})
import { nextTestSetup } from 'e2e-utils'
describe('next-config-ts-import-json-esm', () => {
// TODO: Remove this once we bump minimum Node.js version to v22
if (!(process.features as any).typescript) {
it.skip('requires `process.features.typescript` to feature detect Node.js native TS', () => {})
return
}
const { next } = nextTestSetup({
files: __dirname,
packageJson: {
type: 'module',
},
})
it('should support import json (ESM)', async () => {
const $ = await next.render$('/')
expect($('p').text()).toBe('foo')
})
})
import type { NextConfig } from 'next'
import fooJson from './foo.json' with { type: 'json' }
// top-level await will only work in Native TS mode.
// This is to ensure that the test is running in Native TS mode.
await Promise.resolve()
export default {
env: {
foo: fooJson.foo,
},
} satisfies NextConfig
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>{process.env.foobarbaz}</p>
}
import { baz } from './baz.ts'
export const barbaz = 'bar' + baz
import { barbaz } from './bar.ts'
export const foobarbaz = 'foo' + barbaz
import { nextTestSetup } from 'e2e-utils'
describe('next-config-ts-nested-imports-cjs', () => {
// TODO: Remove this once we bump minimum Node.js version to v22
if (!(process.features as any).typescript) {
it.skip('requires `process.features.typescript` to feature detect Node.js native TS', () => {})
return
}
const { next } = nextTestSetup({
files: __dirname,
})
it('should handle nested imports (CJS)', async () => {
const $ = await next.render$('/')
expect($('p').text()).toBe('foobarbaz')
})
})
import { nextTestSetup } from 'e2e-utils'
describe('next-config-ts-nested-imports-esm', () => {
// TODO: Remove this once we bump minimum Node.js version to v22
if (!(process.features as any).typescript) {
it.skip('requires `process.features.typescript` to feature detect Node.js native TS', () => {})
return
}
const { next } = nextTestSetup({
files: __dirname,
packageJson: {
type: 'module',
},
})
it('should handle nested imports (ESM)', async () => {
const $ = await next.render$('/')
expect($('p').text()).toBe('foobarbaz')
})
})
import type { NextConfig } from 'next'
import { foobarbaz } from './foo.ts'
// top-level await will only work in Native TS mode.
// This is to ensure that the test is running in Native TS mode.
await Promise.resolve()
const nextConfig: NextConfig = {
env: {
foobarbaz,
},
}
export default nextConfig
{
"compilerOptions": {
"allowImportingTsExtensions": true
}
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>{process.env.foo}</p>
}
import { nextTestSetup } from 'e2e-utils'
describe('next-config-ts-node-api-cjs', () => {
// TODO: Remove this once we bump minimum Node.js version to v22
if (!(process.features as any).typescript) {
it.skip('requires `process.features.typescript` to feature detect Node.js native TS', () => {})
return
}
const { next } = nextTestSetup({
files: __dirname,
})
it('should be able to use Node.js API (CJS)', async () => {
const $ = await next.render$('/')
expect($('p').text()).toBe('foo')
})
})
import type { NextConfig } from 'next'
import fs from 'node:fs'
import { join } from 'node:path'
// top-level await will only work in Native TS mode.
// This is to ensure that the test is running in Native TS mode.
await Promise.resolve()
const foo = fs.readFileSync(join('.', 'foo.txt'), 'utf8')
const nextConfig: NextConfig = {
env: {
foo,
},
}
export default nextConfig
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>{process.env.foo}</p>
}
import { nextTestSetup } from 'e2e-utils'
describe('next-config-ts-node-api-esm', () => {
// TODO: Remove this once we bump minimum Node.js version to v22
if (!(process.features as any).typescript) {
it.skip('requires `process.features.typescript` to feature detect Node.js native TS', () => {})
return
}
const { next } = nextTestSetup({
files: __dirname,
packageJson: {
type: 'module',
},
})
it('should be able to use Node.js API (ESM)', async () => {
const $ = await next.render$('/')
expect($('p').text()).toBe('foo')
})
})
import type { NextConfig } from 'next'
import fs from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
// top-level await will only work in Native TS mode.
// This is to ensure that the test is running in Native TS mode.
await Promise.resolve()
// import.meta.url only works in ESM
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const foo = fs.readFileSync(join(__dirname, 'foo.txt'), 'utf8')
const nextConfig: NextConfig = {
env: {
foo,
},
}
export default nextConfig
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
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