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 @@
"plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/stylistic"
],
"files": ["**/*.ts", "**/*.tsx"],
"files": ["**/*.ts", "**/*.tsx", "**/*.mts"],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"sourceType": "module",
......
......@@ -561,9 +561,7 @@ jobs:
with:
nodeVersion: ${{ matrix.node }}
afterBuild: |
export NEXT_TEST_MODE=dev
export NODE_OPTIONS=--experimental-transform-types
node run-tests.js test/e2e/app-dir/next-config-ts-native-ts/**/*.test.ts
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
stepName: 'test-next-config-ts-native-ts-dev-${{ matrix.node }}'
secrets: inherit
......@@ -583,9 +581,7 @@ jobs:
with:
nodeVersion: ${{ matrix.node }}
afterBuild: |
export NEXT_TEST_MODE=start
export NODE_OPTIONS=--experimental-transform-types
node run-tests.js test/e2e/app-dir/next-config-ts-native-ts/**/*.test.ts
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
stepName: 'test-next-config-ts-native-ts-prod-${{ matrix.node }}'
secrets: inherit
......
......@@ -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"]
}
......@@ -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"]
}
......@@ -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"]
}
......@@ -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"]
}
......@@ -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"]
}
......@@ -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"]
}
......@@ -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"]
}
......@@ -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"]
}
......@@ -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"]
}
......@@ -122,6 +122,7 @@ export async function transpileConfig({
// Node.js v22.10.0+
// Value is 'strip' or 'transform' based on how the feature is enabled.
// 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) {
// Run import() here to catch errors and fallback to legacy resolution.
return (await import(pathToFileURL(nextConfigPath).href)).default
......
......@@ -3,6 +3,8 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
// eslint-disable-next-line import/no-extraneous-dependencies
import ts from 'typescript'
// eslint-disable-next-line import/no-extraneous-dependencies
import stripAnsi from 'strip-ansi'
import { writeConfigurationDefaults } from './writeConfigurationDefaults'
describe('writeConfigurationDefaults()', () => {
......@@ -46,53 +48,51 @@ describe('writeConfigurationDefaults()', () => {
hasPagesDir
)
const tsConfig = await readFile(tsConfigPath, { encoding: 'utf8' })
expect(JSON.parse(tsConfig)).toMatchInlineSnapshot(`
{
"compilerOptions": {
"allowJs": true,
"esModuleInterop": true,
"incremental": true,
"isolatedModules": true,
"jsx": "react-jsx",
"lib": [
"dom",
"dom.iterable",
"esnext",
],
"module": "esnext",
"moduleResolution": "node",
"noEmit": true,
"plugins": [
{
"name": "next",
},
],
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": false,
"target": "ES2017",
},
"exclude": [
"node_modules",
],
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
"**/*.ts",
"**/*.tsx",
],
}
`)
expect(
consoleLogSpy.mock.calls
.flat()
.join('\n')
// eslint-disable-next-line no-control-regex
.replace(/\x1B\[\d+m/g, '') // remove color control characters
).toMatchInlineSnapshot(`
const tsConfig = JSON.parse(
await readFile(tsConfigPath, { encoding: 'utf8' })
)
expect(tsConfig).toMatchInlineSnapshot(`
{
"compilerOptions": {
"allowJs": true,
"esModuleInterop": true,
"incremental": true,
"isolatedModules": true,
"jsx": "react-jsx",
"lib": [
"dom",
"dom.iterable",
"esnext",
],
"module": "esnext",
"moduleResolution": "node",
"noEmit": true,
"plugins": [
{
"name": "next",
},
],
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": false,
"target": "ES2017",
},
"exclude": [
"node_modules",
],
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
"**/*.mts",
"**/*.ts",
"**/*.tsx",
],
}
`)
expect(stripAnsi(consoleLogSpy.mock.calls.flat().join('\n')))
.toMatchInlineSnapshot(`
"
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:
......@@ -104,7 +104,7 @@ describe('writeConfigurationDefaults()', () => {
- strict was set to false
- noEmit 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' }
- exclude was set to ['node_modules']
......@@ -136,13 +136,9 @@ describe('writeConfigurationDefaults()', () => {
hasPagesDir
)
expect(
consoleLogSpy.mock.calls
.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.')
expect(stripAnsi(consoleLogSpy.mock.calls.flat().join('\n'))).not.toMatch(
'Strict-mode is set to false by default.'
)
})
describe('with tsconfig extends', () => {
......@@ -155,7 +151,7 @@ describe('writeConfigurationDefaults()', () => {
})
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 baseContent = { include }
......@@ -202,11 +198,12 @@ describe('writeConfigurationDefaults()', () => {
const parsed = JSON.parse(output)
expect(parsed.include.sort()).toMatchInlineSnapshot(`
[
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
]
[
"**/*.mts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
]
`)
})
......
......@@ -212,44 +212,56 @@ export async function writeConfigurationDefaults(
if (!('include' in rawConfig)) {
userTsConfig.include = hasAppDir
? ['next-env.d.ts', nextAppTypes, '**/*.ts', '**/*.tsx']
: ['next-env.d.ts', '**/*.ts', '**/*.tsx']
? ['next-env.d.ts', nextAppTypes, '**/*.mts', '**/*.ts', '**/*.tsx']
: ['next-env.d.ts', '**/*.mts', '**/*.ts', '**/*.tsx']
suggestedActions.push(
cyan('include') +
' was set to ' +
bold(
hasAppDir
? `['next-env.d.ts', '${nextAppTypes}', '**/*.ts', '**/*.tsx']`
: `['next-env.d.ts', '**/*.ts', '**/*.tsx']`
? `['next-env.d.ts', '${nextAppTypes}', '**/*.mts', '**/*.ts', '**/*.tsx']`
: `['next-env.d.ts', '**/*.mts', '**/*.ts', '**/*.tsx']`
)
)
} else if (hasAppDir && !rawConfig.include.includes(nextAppTypes)) {
if (!Array.isArray(userTsConfig.include)) {
userTsConfig.include = []
} else if (hasAppDir) {
const missingFromResolved = []
if (!rawConfig.include.includes(nextAppTypes)) {
missingFromResolved.push(nextAppTypes)
}
// rawConfig will resolve all extends and include paths (ex: tsconfig.json, tsconfig.base.json, etc.)
// if it doesn't match userTsConfig then update the userTsConfig to add the
// rawConfig's includes in addition to nextAppTypes
if (
rawConfig.include.length !== userTsConfig.include.length ||
JSON.stringify(rawConfig.include.sort()) !==
JSON.stringify(userTsConfig.include.sort())
) {
userTsConfig.include.push(...rawConfig.include, nextAppTypes)
suggestedActions.push(
cyan('include') +
' was set to ' +
bold(
`[${[...rawConfig.include, nextAppTypes]
.map((i) => `'${i}'`)
.join(', ')}]`
if (!rawConfig.include.includes('**/*.mts')) {
missingFromResolved.push('**/*.mts')
}
if (missingFromResolved.length > 0) {
if (!Array.isArray(userTsConfig.include)) {
userTsConfig.include = []
}
// rawConfig will resolve all extends and include paths (ex: tsconfig.json, tsconfig.base.json, etc.)
// if it doesn't match userTsConfig then update the userTsConfig to add the
// rawConfig's includes in addition to missing items
if (
rawConfig.include.length !== userTsConfig.include.length ||
JSON.stringify(rawConfig.include.sort()) !==
JSON.stringify(userTsConfig.include.sort())
) {
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(
[
`${configBaseName}.cjs`,
`${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}.jsx`,
`${configBaseName}.tsx`,
......
......@@ -109,6 +109,9 @@ export const CONFIG_FILES = [
'next.config.js',
'next.config.mjs',
'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 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