Unverified Commit dad4c323 authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

feat(next): `next.config.ts` (#63051)

> Note: port of #57656

## What?

This PR initiated support of `next.config.ts`.

Follow ups:

- update docs
([x-ref](https://github.com/vercel/next.js/pull/63051/commits/2ea9b6e2c77b71ae9406032a33e1c20c6053e503))
- update cna ts templates
([x-ref](https://github.com/vercel/next.js/pull/63051/commits/80e674036edfc0307331d3f604b1399043bb65e6))

## Why?

> Next.js provides a TypeScript-first development experience for
building your React application.

This PR can resolve the two main needs:

1. Import TS files to the config.
2. Conduct a type check directly by importing `type` instead of JSDoc.

x-ref: #5318 #35969 #44632 #50121 #50126

## How?

### Goals

- [x] [do not
bundle](https://github.com/vercel/next.js/pull/57656#discussion_r1499983515)
- [x] [minimum fs
operations](https://github.com/vercel/next.js/pull/63051#discussion_r1550609199)
- [x] zero restrictions

Used `require.extensions` hooks to transpile the imported files on the
fly.

To reduce I/O operation on disk, used custom `module.exports` to require
directly from a transpiled code string.

## Expected

> Added tests for the cases below:

- [x] export default
- [x] export config `as default`
- [x] [config as an async
function](https://nextjs.org/docs/app/api-reference/next-config-js)
- [x] use Node.js modules (fs, path, etc.)
- [x] HMR on config change
- [x] throw when type error
- [x] turbopack

### Importing Files

- [x] nested imports (config -> A -> B)
- [x] import alias (tsconfig baseUrl and paths)
- [x] import from `node_modules`
- [x] import `JSON`

#### Extensions

- [x] `.ts`
- [x] `.cts`
- [x] `.mts`
- [x] `.cjs`
- [x] `.mjs`
- [x] `.js` (both ESM and CJS w/o extra change)

---------
Co-authored-by: 's avatarDonny/강동윤 <kdy1997.dev@gmail.com>
Co-authored-by: 's avatarSukka <isukkaw@gmail.com>
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
Co-authored-by: 's avatarSam Ko <sam@vercel.com>
Co-authored-by: 's avatarAhmed Abdelbaset <A7med3bdulBaset@gmail.com>
Co-authored-by: 's avatarJJ Kasper <22380829+ijjk@users.noreply.github.com>
parent deab0f68
......@@ -9,7 +9,7 @@ import { hasNecessaryDependencies } from '../lib/has-necessary-dependencies'
let TSCONFIG_WARNED = false
function parseJsonFile(filePath: string) {
export function parseJsonFile(filePath: string) {
const JSON5 = require('next/dist/compiled/json5')
const contents = readFileSync(filePath, 'utf8')
......
import type { Options as SWCOptions } from '@swc/core'
import Module from 'node:module'
import { readFileSync } from 'node:fs'
import { dirname } from 'node:path'
const oldJSHook = require.extensions['.js']
const extensions = ['.ts', '.cts', '.mts', '.cjs', '.mjs']
export function registerHook(swcOptions: SWCOptions) {
// lazy require swc since it loads React before even setting NODE_ENV
// resulting loading Development React on Production
const { transformSync } = require('../swc')
require.extensions['.js'] = function (mod: any, oldFilename) {
try {
return oldJSHook(mod, oldFilename)
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ERR_REQUIRE_ESM') {
throw error
}
// calling oldJSHook throws ERR_REQUIRE_ESM, so run _compile manually
// TODO: investigate if we can remove readFileSync
const content = readFileSync(oldFilename, 'utf8')
const { code } = transformSync(content, swcOptions)
mod._compile(code, oldFilename)
}
}
for (const ext of extensions) {
const oldHook = require.extensions[ext] ?? oldJSHook
require.extensions[ext] = function (mod: any, oldFilename) {
const _compile = mod._compile
mod._compile = function (code: string, filename: string) {
const swc = transformSync(code, swcOptions)
return _compile.call(this, swc.code, filename)
}
return oldHook(mod, oldFilename)
}
}
}
export function deregisterHook() {
require.extensions['.js'] = oldJSHook
extensions.forEach((ext) => delete require.extensions[ext])
}
export function requireFromString(code: string, filename: string) {
const paths = (Module as any)._nodeModulePaths(dirname(filename))
const m = new Module(filename, module.parent!) as any
m.paths = paths
m._compile(code, filename)
return m.exports
}
import type { Options as SWCOptions } from '@swc/core'
import type { CompilerOptions } from 'typescript'
import { join } from 'node:path'
import { readFile } from 'node:fs/promises'
import { deregisterHook, registerHook, requireFromString } from './require-hook'
import { parseJsonFile } from '../load-jsconfig'
function resolveSWCOptions(
cwd: string,
compilerOptions: CompilerOptions
): SWCOptions {
const resolvedBaseUrl = join(cwd, compilerOptions.baseUrl ?? '.')
return {
jsc: {
target: 'es5',
parser: {
syntax: 'typescript',
},
paths: compilerOptions.paths,
baseUrl: resolvedBaseUrl,
},
module: {
type: 'commonjs',
},
isModule: 'unknown',
} satisfies SWCOptions
}
async function lazilyGetTSConfig(cwd: string) {
let tsConfig: { compilerOptions: CompilerOptions }
try {
tsConfig = parseJsonFile(join(cwd, 'tsconfig.json'))
} catch (error) {
// ignore if tsconfig.json does not exist
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
throw error
}
tsConfig = { compilerOptions: {} }
}
return tsConfig
}
export async function transpileConfig({
nextConfigPath,
cwd,
}: {
nextConfigPath: string
cwd: string
}) {
let hasRequire = false
try {
const { compilerOptions } = await lazilyGetTSConfig(cwd)
const swcOptions = resolveSWCOptions(cwd, compilerOptions)
const nextConfigString = await readFile(nextConfigPath, 'utf8')
// lazy require swc since it loads React before even setting NODE_ENV
// resulting loading Development React on Production
const { transform } = require('../swc')
const { code } = await transform(nextConfigString, swcOptions)
// register require hook only if require exists
if (code.includes('require(')) {
registerHook(swcOptions)
hasRequire = true
}
// filename & extension don't matter here
return requireFromString(code, join(cwd, 'next.config.compiled.js'))
} catch (error) {
throw error
} finally {
if (hasRequire) {
deregisterHook()
}
}
}
......@@ -25,6 +25,7 @@ import { matchRemotePattern } from '../shared/lib/match-remote-pattern'
import { ZodParsedType, util as ZodUtil } from 'next/dist/compiled/zod'
import type { ZodError, ZodIssue } from 'next/dist/compiled/zod'
import { hasNextSupport } from '../telemetry/ci-info'
import { transpileConfig } from '../build/next-config-ts/transpile-config'
export { normalizeConfig } from './config-shared'
export type { DomainLocale, NextConfig } from './config-shared'
......@@ -984,8 +985,8 @@ export default async function loadConfig(
// If config file was found
if (path?.length) {
configFileName = basename(path)
let userConfigModule: any
let userConfigModule: any
try {
const envBefore = Object.assign({}, process.env)
......@@ -997,6 +998,14 @@ export default async function loadConfig(
// jest relies on so we fall back to require for this case
// https://github.com/nodejs/node/issues/35889
userConfigModule = require(path)
} else if (configFileName === 'next.config.ts') {
userConfigModule = await transpileConfig({
nextConfigPath: path,
cwd: dir,
})
curLog.warn(
`Configuration with ${configFileName} is currently an experimental feature, use with caution.`
)
} else {
userConfigModule = await import(pathToFileURL(path).href)
}
......@@ -1013,11 +1022,13 @@ export default async function loadConfig(
return userConfigModule
}
} catch (err) {
// TODO: Modify docs to add cases of failing next.config.ts transformation
curLog.error(
`Failed to load ${configFileName}, see more info here https://nextjs.org/docs/messages/next-config-error`
)
throw err
}
const userConfig = await normalizeConfig(
phase,
userConfigModule.default || userConfigModule
......@@ -1120,20 +1131,19 @@ export default async function loadConfig(
return completeConfig
} else {
const configBaseName = basename(CONFIG_FILES[0], extname(CONFIG_FILES[0]))
const nonJsPath = findUp.sync(
const unsupportedConfig = findUp.sync(
[
`${configBaseName}.jsx`,
`${configBaseName}.ts`,
`${configBaseName}.tsx`,
`${configBaseName}.json`,
],
{ cwd: dir }
)
if (nonJsPath?.length) {
if (unsupportedConfig?.length) {
throw new Error(
`Configuring Next.js via '${basename(
nonJsPath
)}' is not supported. Please replace the file with 'next.config.js' or 'next.config.mjs'.`
unsupportedConfig
)}' is not supported. Please replace the file with 'next.config.js', 'next.config.mjs', or 'next.config.ts'.`
)
}
}
......
......@@ -50,7 +50,11 @@ export const DEV_CLIENT_MIDDLEWARE_MANIFEST = '_devMiddlewareManifest.json'
export const REACT_LOADABLE_MANIFEST = 'react-loadable-manifest.json'
export const AUTOMATIC_FONT_OPTIMIZATION_MANIFEST = 'font-manifest.json'
export const SERVER_DIRECTORY = 'server'
export const CONFIG_FILES = ['next.config.js', 'next.config.mjs']
export const CONFIG_FILES = [
'next.config.js',
'next.config.mjs',
'next.config.ts',
]
export const BUILD_ID_FILE = 'BUILD_ID'
export const BLOCKED_PAGES = ['/_document', '/_app', '/_error']
export const CLIENT_PUBLIC_FILES_PATH = 'public'
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
describe('next-config-ts - dev-hmr', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should output config file change', async () => {
await check(async () => next.cliOutput, /ready/i)
await check(async () => {
await next.patchFile('next.config.ts', (content) => {
return content.replace(
'// target',
`async redirects() {
return [
{
source: '/about',
destination: '/',
permanent: false,
},
]
},`
)
})
return next.cliOutput
}, /Found a change in next\.config\.ts\. Restarting the server to apply the changes\.\.\./)
await check(() => next.fetch('/about').then((res) => res.status), 200)
})
})
import type { NextConfig } from 'next'
const nextConfig = {
// target
} satisfies NextConfig
export default nextConfig
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 - turbopack', () => {
const { next } = nextTestSetup({
files: __dirname,
// explicitly ensure that turbopack is used
startCommand: 'pnpm next dev --turbo',
})
it('should work with Turbopack', async () => {
const $ = await next.render$('/')
expect($('p').text()).toBe('foo')
})
})
import type { NextConfig } from 'next'
const nextConfig = {
env: {
foo: 'foo',
},
} satisfies NextConfig
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-config-as-async-function', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should support config as async function', async () => {
const $ = await next.render$('/')
expect($('p').text()).toBe('foo')
})
})
import type { NextConfig } from 'next'
const nextConfigAsyncFunction = async (phase, { defaultConfig }) => {
const nextConfig: NextConfig = {
...defaultConfig,
env: {
foo: phase ? 'foo' : 'bar',
},
}
return nextConfig
}
export default nextConfigAsyncFunction
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', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should support export { x as default }', async () => {
const $ = await next.render$('/')
expect($('p').text()).toBe('foo')
})
})
import type { NextConfig } from 'next'
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', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should support export default { ... }', async () => {
const $ = await next.render$('/')
expect($('p').text()).toBe('foo')
})
})
import type { NextConfig } from 'next'
export default {
env: {
foo: 'foo',
},
} satisfies NextConfig
import { nextTestSetup } from 'e2e-utils'
describe('next-config-ts-import-alias', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should support import alias', async () => {
const $ = await next.render$('/')
expect($('p').text()).toBe('foobar')
})
})
import type { NextConfig } from 'next'
import { foo } from '@/foo'
import { bar } from 'bar'
const nextConfig: NextConfig = {
env: {
foo,
bar,
},
}
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 + process.env.bar}`}</p>
}
/**
* comment
*/
{
"compilerOptions": {
"jsx": "preserve",
/* comment */
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"] // comment
}
}
}
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-from-node-modules', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should import from node_modules', async () => {
const $ = await next.render$('/')
expect($('p').text()).toBe('foo')
})
})
import type { NextConfig } from 'next'
import { foo } from 'foo'
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-import-json', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should support import json', async () => {
const $ = await next.render$('/')
expect($('p').text()).toBe('foo')
})
})
import type { NextConfig } from 'next'
import { foo } from './foo.json'
export default {
env: {
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'
export const barbaz = 'bar' + baz
import { barbaz } from './bar'
export const foobarbaz = 'foo' + barbaz
import { nextTestSetup } from 'e2e-utils'
describe('next-config-ts-nested-imports', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should handle nested imports', async () => {
const $ = await next.render$('/')
expect($('p').text()).toBe('foobarbaz')
})
})
import type { NextConfig } from 'next'
import { foobarbaz } from './foo'
const nextConfig: NextConfig = {
env: {
foobarbaz,
},
}
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', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should be able to use Node.js API', 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'
const foo = fs.readFileSync(join(__dirname, '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>
{JSON.stringify([
process.env.cjs,
process.env.mjs,
process.env.cts,
process.env.mts,
process.env.ts,
process.env.commonjs,
])}
</p>
)
}
import { nextTestSetup } from 'e2e-utils'
describe('next-config-ts-pkg-commonjs', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should handle ESM modules in CommonJS project', async () => {
const $ = await next.render$('/')
const text = $('p').text()
expect(text).toContain('cjs')
expect(text).toContain('mjs')
expect(text).toContain('cts')
expect(text).toContain('mts')
expect(text).toContain('ts')
expect(text).toContain('commonjs')
})
})
import type { NextConfig } from 'next'
import { cjs } from './fixtures/cjs.cjs'
import { mjs } from './fixtures/mjs.mjs'
import { cts } from './fixtures/cts.cts'
import { mts } from './fixtures/mts.mts'
import { ts } from './fixtures/ts'
import { commonjs } from './fixtures/commonjs'
const nextConfig: NextConfig = {
env: {
cjs,
mjs,
cts,
mts,
ts,
commonjs,
},
}
export default nextConfig
{
"compilerOptions": {
"jsx": "preserve",
"lib": ["ESNext"],
"allowImportingTsExtensions": true,
"allowJs": true,
"noEmit": 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.cjs,
process.env.mjs,
process.env.cts,
process.env.mts,
process.env.ts,
process.env.esm,
])}
</p>
)
}
import { nextTestSetup } from 'e2e-utils'
describe('next-config-ts-pkg-module', () => {
const { next } = nextTestSetup({
files: __dirname,
packageJson: { type: 'module' },
})
it('should handle ESM modules in CommonJS project', async () => {
const $ = await next.render$('/')
const text = $('p').text()
expect(text).toContain('cjs')
expect(text).toContain('mjs')
expect(text).toContain('cts')
expect(text).toContain('mts')
expect(text).toContain('ts')
expect(text).toContain('esm')
})
})
import type { NextConfig } from 'next'
import { cjs } from './fixtures/cjs.cjs'
import { mjs } from './fixtures/mjs.mjs'
import { cts } from './fixtures/cts.cts'
import { mts } from './fixtures/mts.mts'
import { ts } from './fixtures/ts'
import { esm } from './fixtures/esm'
const nextConfig: NextConfig = {
env: {
cjs,
mjs,
cts,
mts,
ts,
esm,
},
}
export default nextConfig
{
"compilerOptions": {
"jsx": "preserve",
"lib": ["ESNext"],
"allowImportingTsExtensions": true,
"allowJs": true,
"noEmit": 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-type-error', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
})
if (skipped) {
return
}
it('should throw with type error on build', async () => {
if (isNextDev) {
await next.start()
const $ = await next.render$('/')
expect($('p').text()).toBe('foo')
} else {
const { cliOutput } = await next.build()
await expect(cliOutput).toContain(
`Type error: Type 'string' is not assignable to type 'number'.`
)
}
})
})
import type { NextConfig } from 'next'
// type error
let foo: number = 'foo'
const nextConfig: NextConfig = {
env: {
foo,
},
}
export default nextConfig
......@@ -80,12 +80,12 @@ describe('config', () => {
}).rejects.toThrow(/The "target" property is no longer supported/)
})
it('Should throw an error when next.config.js is not present', async () => {
it('Should throw an error when next.config.(js | mjs | ts) is not present', async () => {
await expect(
async () =>
await loadConfig(
PHASE_DEVELOPMENT_SERVER,
join(__dirname, '_resolvedata', 'typescript-config')
join(__dirname, '_resolvedata', 'missing-config')
)
).rejects.toThrow(
/Configuring Next.js via .+ is not supported. Please replace the file with 'next.config.js'/
......@@ -99,4 +99,12 @@ describe('config', () => {
)
expect(config.__test__ext).toBe('js')
})
it('Should not throw an error when next.config.ts is present', async () => {
const config = await loadConfig(
PHASE_DEVELOPMENT_SERVER,
join(__dirname, '_resolvedata', 'typescript-config')
)
expect(config.__test__ext).toBe('ts')
})
})
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