Unverified Commit 25da5f04 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Move next-env.d.ts to dist dir (#86752)

parent aa8a243e
......@@ -224,6 +224,7 @@ import {
createRouteTypesManifest,
writeRouteTypesManifest,
writeValidatorFile,
writeDynamicTypesFile,
} from '../server/lib/router-utils/route-types-utils'
import { Lockfile } from './lockfile'
import {
......@@ -1484,6 +1485,12 @@ export default async function build(
config
)
await writeValidatorFile(routeTypesManifest, validatorFilePath)
await writeDynamicTypesFile({
distDir,
imageImportsEnabled: !config.images.disableStaticImages,
hasPagesDir: !!pagesDir,
hasAppDir: !!appDir,
})
})
// Turbopack already handles conflicting app and page routes.
......
......@@ -22,7 +22,6 @@ function verifyTypeScriptSetup(
distDir: string,
typeCheckPreflight: boolean,
tsconfigPath: string | undefined,
disableStaticImages: boolean,
cacheDir: string | undefined,
enableWorkerThreads: boolean | undefined,
hasAppDir: boolean,
......@@ -52,7 +51,6 @@ function verifyTypeScriptSetup(
distDir,
typeCheckPreflight,
tsconfigPath,
disableStaticImages,
cacheDir,
hasAppDir,
hasPagesDir,
......@@ -119,7 +117,6 @@ export async function startTypeChecking({
config.distDir,
!ignoreTypeScriptErrors,
config.typescript.tsconfigPath,
config.images.disableStaticImages,
cacheDir,
config.experimental.workerThreads,
!!appDir,
......
......@@ -142,7 +142,6 @@ async function runPlaywright(
distDir: nextConfig.distDir,
typeCheckPreflight: false,
tsconfigPath: nextConfig.typescript.tsconfigPath,
disableStaticImages: nextConfig.images.disableStaticImages,
hasAppDir: !!appDir,
hasPagesDir: !!pagesDir,
isolatedDevBuild: nextConfig.experimental.isolatedDevBuild,
......
......@@ -29,6 +29,7 @@ import {
createRouteTypesManifest,
writeRouteTypesManifest,
writeValidatorFile,
writeDynamicTypesFile,
} from '../server/lib/router-utils/route-types-utils'
import { writeCacheLifeTypes } from '../server/lib/router-utils/cache-life-type-utils'
import { createValidFileMatcher } from '../server/lib/find-page-file'
......@@ -59,7 +60,6 @@ const nextTypegen = async (
distDir: nextConfig.distDir,
typeCheckPreflight: false,
tsconfigPath: nextConfig.typescript.tsconfigPath,
disableStaticImages: nextConfig.images.disableStaticImages,
hasAppDir: !!appDir,
hasPagesDir: !!pagesDir,
isolatedDevBuild: nextConfig.experimental.isolatedDevBuild,
......@@ -171,6 +171,13 @@ const nextTypegen = async (
await writeValidatorFile(routeTypesManifest, validatorFilePath)
await writeDynamicTypesFile({
distDir,
imageImportsEnabled: !nextConfig.images.disableStaticImages,
hasPagesDir: !!pagesDir,
hasAppDir: !!appDir,
})
// Generate cache-life types if cacheLife config exists
const cacheLifeFilePath = join(distDir, 'types', 'cache-life.d.ts')
writeCacheLifeTypes(nextConfig.cacheLife, cacheLifeFilePath)
......
import os from 'os'
import path from 'path'
import { promises as fs } from 'fs'
export async function writeAppTypeDeclarations({
baseDir,
distDir,
imageImportsEnabled,
hasPagesDir,
hasAppDir,
}: {
baseDir: string
distDir: string
imageImportsEnabled: boolean
hasPagesDir: boolean
hasAppDir: boolean
}): Promise<void> {
// Reference `next` types
const appTypeDeclarations = path.join(baseDir, 'next-env.d.ts')
// Defaults EOL to system default
let eol = os.EOL
let currentContent: string | undefined
try {
currentContent = await fs.readFile(appTypeDeclarations, 'utf8')
// If file already exists then preserve its line ending
const lf = currentContent.indexOf('\n', /* skip first so we can lf - 1 */ 1)
if (lf !== -1) {
if (currentContent[lf - 1] === '\r') {
eol = '\r\n'
} else {
eol = '\n'
}
}
} catch {}
/**
* "Triple-slash directives" used to create typings files for Next.js projects
* using Typescript .
*
* @see https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html
*/
const directives: string[] = [
// Include the core Next.js typings.
'/// <reference types="next" />',
]
if (imageImportsEnabled) {
directives.push('/// <reference types="next/image-types/global" />')
}
if (hasAppDir && hasPagesDir) {
directives.push(
'/// <reference types="next/navigation-types/compat/navigation" />'
)
}
const routeTypesPath = path.posix.join(
distDir.replaceAll(path.win32.sep, path.posix.sep),
'types/routes.d.ts'
)
// Use ESM import instead of triple-slash reference for better ESLint compatibility
directives.push(`import "./${routeTypesPath}";`)
// Push the notice in.
directives.push(
'',
'// NOTE: This file should not be edited',
`// see https://nextjs.org/docs/${hasAppDir ? 'app' : 'pages'}/api-reference/config/typescript for more information.`
)
const content = directives.join(eol) + eol
// Avoids an un-necessary write on read-only fs
if (currentContent === content) {
return
}
await fs.writeFile(appTypeDeclarations, content)
}
......@@ -84,7 +84,6 @@ describe('writeConfigurationDefaults()', () => {
"node_modules",
],
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts",
......@@ -107,7 +106,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', '.next/dev/types/**/*.ts', '**/*.mts', '**/*.ts', '**/*.tsx']
- include was set to ['.next/types/**/*.ts', '.next/dev/types/**/*.ts', '**/*.mts', '**/*.ts', '**/*.tsx']
- plugins was updated to add { name: 'next' }
- exclude was set to ['node_modules']
......
......@@ -282,19 +282,16 @@ export async function writeConfigurationDefaults(
)
if (!('include' in userTsConfig)) {
userTsConfig.include = hasAppDir
? ['next-env.d.ts', ...nextAppTypes, '**/*.mts', '**/*.ts', '**/*.tsx']
: ['next-env.d.ts', '**/*.mts', '**/*.ts', '**/*.tsx']
// Always include .next/types for dynamic types (image imports, route types, etc.)
userTsConfig.include = [...nextAppTypes, '**/*.mts', '**/*.ts', '**/*.tsx']
suggestedActions.push(
cyan('include') +
' was set to ' +
bold(
hasAppDir
? `['next-env.d.ts', ${nextAppTypes.map((type) => `'${type}'`).join(', ')}, '**/*.mts', '**/*.ts', '**/*.tsx']`
: `['next-env.d.ts', '**/*.mts', '**/*.ts', '**/*.tsx']`
`[${nextAppTypes.map((type) => `'${type}'`).join(', ')}, '**/*.mts', '**/*.ts', '**/*.tsx']`
)
)
} else if (hasAppDir) {
} else {
const missingFromResolved = []
for (const type of nextAppTypes) {
if (!userTsConfig.include.includes(type)) {
......
......@@ -9,7 +9,6 @@ import * as log from '../build/output/log'
import { getTypeScriptIntent } from './typescript/getTypeScriptIntent'
import type { TypeCheckResult } from './typescript/runTypeCheck'
import { writeAppTypeDeclarations } from './typescript/writeAppTypeDeclarations'
import { writeConfigurationDefaults } from './typescript/writeConfigurationDefaults'
import { installDependencies } from './install-dependencies'
import { isCI } from '../server/ci-info'
......@@ -39,7 +38,6 @@ export async function verifyTypeScriptSetup({
cacheDir,
tsconfigPath,
typeCheckPreflight,
disableStaticImages,
hasAppDir,
hasPagesDir,
isolatedDevBuild,
......@@ -52,7 +50,6 @@ export async function verifyTypeScriptSetup({
cacheDir?: string
tsconfigPath: string | undefined
typeCheckPreflight: boolean
disableStaticImages: boolean
hasAppDir: boolean
hasPagesDir: boolean
isolatedDevBuild: boolean | undefined
......@@ -138,16 +135,6 @@ export async function verifyTypeScriptSetup({
hasPagesDir,
isolatedDevBuild
)
// Write out the necessary `next-env.d.ts` file to correctly register
// Next.js' types:
await writeAppTypeDeclarations({
baseDir: dir,
distDir,
imageImportsEnabled: !disableStaticImages,
hasPagesDir,
hasAppDir,
})
let result
if (typeCheckPreflight) {
const { runTypeCheck } =
......
......@@ -10,6 +10,7 @@ import {
generateRouteTypesFile,
generateLinkTypesFile,
generateValidatorFile,
generateDynamicTypesFile,
} from './typegen'
import { tryToParsePath } from '../../../lib/try-to-parse-path'
import {
......@@ -382,3 +383,35 @@ export async function writeValidatorFile(
await fs.promises.writeFile(filePath, generateValidatorFile(manifest))
}
/**
* Writes the dynamic types file (.next/types/next-env.d.ts) that contains
* config-dependent type references (image imports, navigation compat, etc.)
*/
export async function writeDynamicTypesFile({
distDir,
imageImportsEnabled,
hasPagesDir,
hasAppDir,
}: {
distDir: string
imageImportsEnabled: boolean
hasPagesDir: boolean
hasAppDir: boolean
}) {
const typesDir = path.join(distDir, 'types')
const filePath = path.join(typesDir, 'next-env.d.ts')
// Directory should already be created by writeRouteTypesManifest, but ensure it exists
if (!fs.existsSync(typesDir)) {
await fs.promises.mkdir(typesDir, { recursive: true })
}
const content = generateDynamicTypesFile({
imageImportsEnabled,
hasPagesDir,
hasAppDir,
})
await fs.promises.writeFile(filePath, content)
}
......@@ -85,6 +85,7 @@ import {
createRouteTypesManifest,
writeRouteTypesManifest,
writeValidatorFile,
writeDynamicTypesFile,
} from './route-types-utils'
import { writeCacheLifeTypes } from './cache-life-type-utils'
import { isParallelRouteSegment } from '../../../shared/lib/segment'
......@@ -145,7 +146,6 @@ async function verifyTypeScript(opts: SetupOpts) {
distDir: opts.nextConfig.distDir,
typeCheckPreflight: false,
tsconfigPath: opts.nextConfig.typescript.tsconfigPath,
disableStaticImages: opts.nextConfig.images.disableStaticImages,
hasAppDir: !!opts.appDir,
hasPagesDir: !!opts.pagesDir,
isolatedDevBuild: opts.nextConfig.experimental.isolatedDevBuild,
......@@ -265,6 +265,12 @@ async function startWatcher(
path.join(distTypesDir, 'routes.d.ts'),
opts.nextConfig
)
await writeDynamicTypesFile({
distDir,
imageImportsEnabled: !opts.nextConfig.images.disableStaticImages,
hasPagesDir: !!pagesDir,
hasAppDir: !!appDir,
})
const routesManifestPath = path.join(distDir, ROUTES_MANIFEST)
const routesManifest: DevRoutesManifest = {
......
import type { RouteTypesManifest } from './route-types-utils'
import { isDynamicRoute } from '../../../shared/lib/router/utils/is-dynamic'
/**
* Generates the content for .next/types/next-env.d.ts
* This file contains dynamic type references that depend on project configuration.
*/
export function generateDynamicTypesFile({
imageImportsEnabled,
hasPagesDir,
hasAppDir,
}: {
imageImportsEnabled: boolean
hasPagesDir: boolean
hasAppDir: boolean
}): string {
const directives: string[] = [
// Include the core Next.js typings.
'/// <reference types="next" />',
'// This file is generated automatically by Next.js',
'// Do not edit this file manually',
'',
]
if (imageImportsEnabled) {
directives.push('/// <reference types="next/image-types/global" />')
}
if (hasAppDir && hasPagesDir) {
directives.push(
'/// <reference types="next/navigation-types/compat/navigation" />'
)
}
// Import routes types from the same directory
directives.push('import "./routes.d.ts"')
return directives.join('\n') + '\n'
}
function generateRouteTypes(routesManifest: RouteTypesManifest): string {
const appRoutes = Object.keys(routesManifest.appRoutes).sort()
const pageRoutes = Object.keys(routesManifest.pageRoutes).sort()
......@@ -574,7 +611,7 @@ export function generateValidatorFile(
default: (req: any, res: any) => ReturnType<NextApiHandler>
config?: {
api?: {
bodyParser?: boolean | { sizeLimit?: string }
bodyParser?: boolean | { sizeLimit?: string | number }
responseLimit?: string | number | boolean
externalResolver?: boolean
}
......
......@@ -38,34 +38,35 @@ describe('tsconfig module: preserve', () => {
expect(output).not.toContain('resolveJsonModule')
expect(await next.readFile('tsconfig.json')).toMatchInlineSnapshot(`
"{
"compilerOptions": {
"module": "preserve",
"target": "ES2017",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"noEmit": true,
"incremental": true,
"isolatedModules": true,
"jsx": "react-jsx"
},
"include": [
"next-env.d.ts",
"**/*.mts",
"**/*.ts",
"**/*.tsx"
],
"exclude": [
"node_modules"
]
}
"
"{
"compilerOptions": {
"module": "preserve",
"target": "ES2017",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"noEmit": true,
"incremental": true,
"isolatedModules": true,
"jsx": "react-jsx"
},
"include": [
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts",
"**/*.ts",
"**/*.tsx"
],
"exclude": [
"node_modules"
]
}
"
`)
})
})
......@@ -8,10 +8,15 @@ import {
launchApp,
nextBuild,
killApp,
retry,
} from 'next-test-utils'
const appDir = join(__dirname, '..')
const nextConfig = join(appDir, 'next.config.js')
// Dynamic types (image types, navigation compat) are now generated in .next/types/
// In dev mode with isolatedDevBuild (default), types are in .next/dev/types/
const dynamicTypesFileBuild = join(appDir, '.next/types/next-env.d.ts')
const dynamicTypesFileDev = join(appDir, '.next/dev/types/next-env.d.ts')
let appPort
let app
let output
......@@ -20,6 +25,14 @@ const handleOutput = (msg) => {
output += msg
}
// Helper to read dynamic types file with retry (file may be written async)
async function readDynamicTypesFile(isDev: boolean) {
const filePath = isDev ? dynamicTypesFileDev : dynamicTypesFileBuild
return retry(async () => {
return await fs.readFile(filePath, 'utf8')
})
}
describe('TypeScript Image Component', () => {
;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'production mode',
......@@ -29,10 +42,7 @@ describe('TypeScript Image Component', () => {
expect(stderr).toMatch(/Failed to compile/)
expect(stderr).toMatch(/is not assignable to type/)
expect(code).toBe(1)
const envTypes = await fs.readFile(
join(appDir, 'next-env.d.ts'),
'utf8'
)
const envTypes = await readDynamicTypesFile(false)
expect(envTypes).toContain('image-types/global')
})
......@@ -47,10 +57,7 @@ describe('TypeScript Image Component', () => {
expect(stderr).toMatch(/is not assignable to type/)
expect(code).toBe(1)
await fs.writeFile(nextConfig, content)
const envTypes = await fs.readFile(
join(appDir, 'next-env.d.ts'),
'utf8'
)
const envTypes = await readDynamicTypesFile(false)
expect(envTypes).not.toContain('image-types/global')
})
}
......@@ -69,10 +76,7 @@ describe('TypeScript Image Component', () => {
afterAll(() => killApp(app))
it('should have image types when enabled', async () => {
const envTypes = await fs.readFile(
join(appDir, 'next-env.d.ts'),
'utf8'
)
const envTypes = await readDynamicTypesFile(true)
expect(envTypes).toContain('image-types/global')
})
......@@ -99,7 +103,7 @@ describe('TypeScript Image Component', () => {
const app = await launchApp(appDir, await findPort())
await killApp(app)
await fs.writeFile(nextConfig, content)
const envTypes = await fs.readFile(join(appDir, 'next-env.d.ts'), 'utf8')
const envTypes = await readDynamicTypesFile(true)
expect(envTypes).not.toContain('image-types/global')
})
})
......
......@@ -8,10 +8,15 @@ import {
launchApp,
nextBuild,
killApp,
retry,
} from 'next-test-utils'
const appDir = join(__dirname, '..')
const nextConfig = join(appDir, 'next.config.js')
// Dynamic types (image types, navigation compat) are now generated in .next/types/
// In dev mode with isolatedDevBuild (default), types are in .next/dev/types/
const dynamicTypesFileBuild = join(appDir, '.next/types/next-env.d.ts')
const dynamicTypesFileDev = join(appDir, '.next/dev/types/next-env.d.ts')
let appPort
let app
let output
......@@ -20,6 +25,14 @@ const handleOutput = (msg) => {
output += msg
}
// Helper to read dynamic types file with retry (file may be written async)
async function readDynamicTypesFile(isDev: boolean) {
const filePath = isDev ? dynamicTypesFileDev : dynamicTypesFileBuild
return retry(async () => {
return await fs.readFile(filePath, 'utf8')
})
}
describe('TypeScript Image Component', () => {
;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'production mode',
......@@ -29,10 +42,7 @@ describe('TypeScript Image Component', () => {
expect(stderr).toMatch(/Failed to compile/)
expect(stderr).toMatch(/is not assignable to type/)
expect(code).toBe(1)
const envTypes = await fs.readFile(
join(appDir, 'next-env.d.ts'),
'utf8'
)
const envTypes = await readDynamicTypesFile(false)
expect(envTypes).toContain('image-types/global')
})
......@@ -47,10 +57,7 @@ describe('TypeScript Image Component', () => {
expect(stderr).toMatch(/is not assignable to type/)
expect(code).toBe(1)
await fs.writeFile(nextConfig, content)
const envTypes = await fs.readFile(
join(appDir, 'next-env.d.ts'),
'utf8'
)
const envTypes = await readDynamicTypesFile(false)
expect(envTypes).not.toContain('image-types/global')
})
}
......@@ -69,10 +76,7 @@ describe('TypeScript Image Component', () => {
afterAll(() => killApp(app))
it('should have image types when enabled', async () => {
const envTypes = await fs.readFile(
join(appDir, 'next-env.d.ts'),
'utf8'
)
const envTypes = await readDynamicTypesFile(true)
expect(envTypes).toContain('image-types/global')
})
......@@ -98,7 +102,7 @@ describe('TypeScript Image Component', () => {
const app = await launchApp(appDir, await findPort())
await killApp(app)
await fs.writeFile(nextConfig, content)
const envTypes = await fs.readFile(join(appDir, 'next-env.d.ts'), 'utf8')
const envTypes = await readDynamicTypesFile(true)
expect(envTypes).not.toContain('image-types/global')
})
})
......@@ -52,7 +52,6 @@ import path from 'path'
"strictNullChecks": true
},
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts",
......@@ -109,7 +108,6 @@ import path from 'path'
"strictNullChecks": true
},
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts",
......@@ -185,7 +183,6 @@ import path from 'path'
// in-object comment 2
,
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts",
......@@ -240,7 +237,6 @@ import path from 'path'
"strictNullChecks": true
},
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts",
......@@ -294,7 +290,6 @@ import path from 'path'
"strictNullChecks": true
},
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts",
......@@ -352,7 +347,6 @@ import path from 'path'
"strictNullChecks": true
},
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts",
......@@ -410,7 +404,6 @@ import path from 'path'
"strictNullChecks": true
},
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts",
......@@ -465,7 +458,6 @@ import path from 'path'
"strictNullChecks": true
},
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts",
......@@ -523,7 +515,6 @@ import path from 'path'
"strictNullChecks": true
},
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts",
......@@ -581,7 +572,6 @@ import path from 'path'
"strictNullChecks": true
},
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts",
......@@ -629,7 +619,6 @@ import path from 'path'
"strictNullChecks": true
},
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
"**/*.mts",
"**/*.ts",
......@@ -688,7 +677,6 @@ import path from 'path'
"strictNullChecks": true
},
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
"**/*.mts",
"**/*.ts",
......@@ -750,7 +738,6 @@ import path from 'path'
"strictNullChecks": true
},
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
"**/*.mts",
"**/*.ts",
......@@ -821,7 +808,6 @@ import path from 'path'
"strictNullChecks": true
},
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
"**/*.ts",
"**/*.tsx"
......
/// <reference types="next" />
/// <reference types="next/image-types/global" />
import "./.next/dev/types/routes.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.
......@@ -5,53 +5,61 @@ import { findPort, launchApp, killApp } from 'next-test-utils'
import { promises as fs } from 'fs'
const appDir = join(__dirname, '..')
const appTypeDeclarations = join(appDir, 'next-env.d.ts')
const rootTypeDeclarations = join(appDir, 'next-env.d.ts')
const distTypeDeclarations = join(appDir, '.next/dev/types/next-env.d.ts')
describe('TypeScript App Type Declarations', () => {
it('should write a new next-env.d.ts if none exist', async () => {
const prevContent = await fs.readFile(appTypeDeclarations, 'utf8')
it('should not create next-env.d.ts in project root', async () => {
// Ensure no next-env.d.ts exists before starting
try {
await fs.unlink(appTypeDeclarations)
const appPort = await findPort()
let app
try {
app = await launchApp(appDir, appPort, {})
const content = await fs.readFile(appTypeDeclarations, 'utf8')
expect(content).toEqual(prevContent)
} finally {
await killApp(app)
}
await fs.unlink(rootTypeDeclarations)
} catch {
// File doesn't exist, which is fine
}
const appPort = await findPort()
let app
try {
app = await launchApp(appDir, appPort, {})
// Verify next-env.d.ts was NOT created in project root
await expect(fs.access(rootTypeDeclarations)).rejects.toThrow()
} finally {
await fs.writeFile(appTypeDeclarations, prevContent)
await killApp(app)
}
})
it('should overwrite next-env.d.ts if an incorrect one exists', async () => {
const prevContent = await fs.readFile(appTypeDeclarations, 'utf8')
it('should not modify existing next-env.d.ts in project root', async () => {
const existingContent = '// custom next-env.d.ts content\n'
await fs.writeFile(rootTypeDeclarations, existingContent)
const prevStat = await fs.stat(rootTypeDeclarations)
const appPort = await findPort()
let app
try {
await fs.writeFile(appTypeDeclarations, prevContent + 'modification')
const appPort = await findPort()
let app
try {
app = await launchApp(appDir, appPort, {})
const content = await fs.readFile(appTypeDeclarations, 'utf8')
expect(content).toEqual(prevContent)
} finally {
await killApp(app)
}
app = await launchApp(appDir, appPort, {})
// Verify next-env.d.ts was NOT modified
const stat = await fs.stat(rootTypeDeclarations)
expect(stat.mtime).toEqual(prevStat.mtime)
const content = await fs.readFile(rootTypeDeclarations, 'utf8')
expect(content).toEqual(existingContent)
} finally {
await fs.writeFile(appTypeDeclarations, prevContent)
await killApp(app)
// Clean up
await fs.unlink(rootTypeDeclarations).catch(() => {})
}
})
it('should not touch an existing correct next-env.d.ts', async () => {
const prevStat = await fs.stat(appTypeDeclarations)
it('should generate next-env.d.ts in .next/types', async () => {
// Clean up any existing .next directory
await fs.rm(join(appDir, '.next'), { recursive: true, force: true })
const appPort = await findPort()
let app
try {
app = await launchApp(appDir, appPort, {})
const stat = await fs.stat(appTypeDeclarations)
expect(stat.mtime).toEqual(prevStat.mtime)
// Verify next-env.d.ts was generated in .next/types
const content = await fs.readFile(distTypeDeclarations, 'utf8')
expect(content).toContain('/// <reference types="next" />')
} finally {
await killApp(app)
}
......
......@@ -17,5 +17,10 @@
"isolatedModules": true
},
"exclude": ["node_modules", "**/*.test.ts", "**/*.test.tsx"],
"include": ["next-env.d.ts", "components", "pages"]
"include": [
"components",
"pages",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
]
}
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.
......@@ -22,6 +22,6 @@
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"include": ["**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
......@@ -19994,17 +19994,6 @@
"flakey": [],
"runtimeError": false
},
"test/integration/typescript-app-type-declarations/test/index.test.ts": {
"passed": [
"TypeScript App Type Declarations should not touch an existing correct next-env.d.ts",
"TypeScript App Type Declarations should overwrite next-env.d.ts if an incorrect one exists",
"TypeScript App Type Declarations should write a new next-env.d.ts if none exist"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/integration/typescript-baseurl/test/index.test.ts": {
"passed": ["TypeScript Features default behavior should render the page"],
"failed": [],
......@@ -22109,5 +22098,16 @@
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/integration/typescript-app-type-declarations/test/index.test.ts": {
"passed": [
"TypeScript App Type Declarations should not create next-env.d.ts in project root",
"TypeScript App Type Declarations should not modify existing next-env.d.ts in project root",
"TypeScript App Type Declarations should overwrite next-env.d.ts in .next/types if incorrect"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
}
}
......@@ -21995,17 +21995,6 @@
"flakey": [],
"runtimeError": false
},
"test/integration/typescript-app-type-declarations/test/index.test.ts": {
"passed": [
"TypeScript App Type Declarations should not touch an existing correct next-env.d.ts",
"TypeScript App Type Declarations should overwrite next-env.d.ts if an incorrect one exists",
"TypeScript App Type Declarations should write a new next-env.d.ts if none exist"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/integration/typescript-baseurl/test/index.test.ts": {
"passed": ["TypeScript Features default behavior should render the page"],
"failed": [],
......@@ -22199,5 +22188,16 @@
],
"flakey": [],
"runtimeError": false
},
"test/integration/typescript-app-type-declarations/test/index.test.ts": {
"passed": [
"TypeScript App Type Declarations should not create next-env.d.ts in project root",
"TypeScript App Type Declarations should not modify existing next-env.d.ts in project root",
"TypeScript App Type Declarations should overwrite next-env.d.ts in .next/types if incorrect"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
}
}
......@@ -17865,17 +17865,6 @@
"flakey": [],
"runtimeError": false
},
"test/integration/typescript-app-type-declarations/test/index.test.ts": {
"passed": [
"TypeScript App Type Declarations should not touch an existing correct next-env.d.ts",
"TypeScript App Type Declarations should overwrite next-env.d.ts if an incorrect one exists",
"TypeScript App Type Declarations should write a new next-env.d.ts if none exist"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/integration/typescript-baseurl/test/index.test.ts": {
"passed": ["TypeScript Features default behavior should render the page"],
"failed": [],
......@@ -19631,5 +19620,16 @@
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/integration/typescript-app-type-declarations/test/index.test.ts": {
"passed": [
"TypeScript App Type Declarations should not create next-env.d.ts in project root",
"TypeScript App Type Declarations should not modify existing next-env.d.ts in project root",
"TypeScript App Type Declarations should overwrite next-env.d.ts in .next/types if incorrect"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
}
}
......@@ -21395,17 +21395,6 @@
"flakey": [],
"runtimeError": false
},
"test/integration/typescript-app-type-declarations/test/index.test.ts": {
"passed": [
"TypeScript App Type Declarations should not touch an existing correct next-env.d.ts",
"TypeScript App Type Declarations should overwrite next-env.d.ts if an incorrect one exists",
"TypeScript App Type Declarations should write a new next-env.d.ts if none exist"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/integration/typescript-baseurl/test/index.test.ts": {
"passed": ["TypeScript Features default behavior should render the page"],
"failed": [],
......@@ -21636,5 +21625,16 @@
],
"flakey": [],
"runtimeError": false
},
"test/integration/typescript-app-type-declarations/test/index.test.ts": {
"passed": [
"TypeScript App Type Declarations should not create next-env.d.ts in project root",
"TypeScript App Type Declarations should not modify existing next-env.d.ts in project root",
"TypeScript App Type Declarations should overwrite next-env.d.ts in .next/types if incorrect"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
}
}
/* eslint-env jest */
import os from 'os'
import fs from 'fs-extra'
import { join } from 'path'
import { writeAppTypeDeclarations } from 'next/dist/lib/typescript/writeAppTypeDeclarations'
const fixtureDir = join(__dirname, 'fixtures/app-declarations')
const declarationFile = join(fixtureDir, 'next-env.d.ts')
const imageImportsEnabled = false
describe('find config', () => {
beforeEach(async () => {
await fs.ensureDir(fixtureDir)
})
afterEach(() => fs.remove(declarationFile))
it('should preserve CRLF EOL', async () => {
const eol = '\r\n'
const content =
'/// <reference types="next" />' +
eol +
(imageImportsEnabled
? '/// <reference types="next/image-types/global" />' + eol
: '') +
`import "./.next/types/routes.d.ts";` +
eol +
eol +
'// NOTE: This file should not be edited' +
eol +
'// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.' +
eol
await fs.writeFile(declarationFile, content)
await writeAppTypeDeclarations({
baseDir: fixtureDir,
distDir: '.next',
imageImportsEnabled,
hasPagesDir: false,
hasAppDir: false,
})
expect(await fs.readFile(declarationFile, 'utf8')).toBe(content)
})
it('should preserve LF EOL', async () => {
const eol = '\n'
const content =
'/// <reference types="next" />' +
eol +
(imageImportsEnabled
? '/// <reference types="next/image-types/global" />' + eol
: '') +
`import "./.next/types/routes.d.ts";` +
eol +
eol +
'// NOTE: This file should not be edited' +
eol +
'// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.' +
eol
await fs.writeFile(declarationFile, content)
await writeAppTypeDeclarations({
baseDir: fixtureDir,
distDir: '.next',
imageImportsEnabled,
hasPagesDir: false,
hasAppDir: false,
})
expect(await fs.readFile(declarationFile, 'utf8')).toBe(content)
})
it('should use OS EOL by default', async () => {
const eol = os.EOL
const content =
'/// <reference types="next" />' +
eol +
(imageImportsEnabled
? '/// <reference types="next/image-types/global" />' + eol
: '') +
`import "./.next/types/routes.d.ts";` +
eol +
eol +
'// NOTE: This file should not be edited' +
eol +
'// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.' +
eol
await writeAppTypeDeclarations({
baseDir: fixtureDir,
distDir: '.next',
imageImportsEnabled,
hasPagesDir: false,
hasAppDir: false,
})
expect(await fs.readFile(declarationFile, 'utf8')).toBe(content)
})
it('should include navigation types if app directory is enabled', async () => {
await writeAppTypeDeclarations({
baseDir: fixtureDir,
distDir: '.next',
imageImportsEnabled,
hasPagesDir: false,
hasAppDir: true,
})
await expect(fs.readFile(declarationFile, 'utf8')).resolves.not.toContain(
'next/navigation-types/compat/navigation'
)
await writeAppTypeDeclarations({
baseDir: fixtureDir,
distDir: '.next',
imageImportsEnabled,
hasPagesDir: true,
hasAppDir: true,
})
await expect(fs.readFile(declarationFile, 'utf8')).resolves.toContain(
'next/navigation-types/compat/navigation'
)
})
})
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