Unverified Commit e27c7fa6 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Honour `distDir` in type generation (#44207)

parent 2c70bc78
...@@ -171,6 +171,7 @@ type SingleCompilerResult = { ...@@ -171,6 +171,7 @@ type SingleCompilerResult = {
*/ */
function verifyTypeScriptSetup( function verifyTypeScriptSetup(
dir: string, dir: string,
distDir: string,
intentDirs: string[], intentDirs: string[],
typeCheckPreflight: boolean, typeCheckPreflight: boolean,
tsconfigPath: string, tsconfigPath: string,
...@@ -197,6 +198,7 @@ function verifyTypeScriptSetup( ...@@ -197,6 +198,7 @@ function verifyTypeScriptSetup(
return typeCheckWorker return typeCheckWorker
.verifyTypeScriptSetup({ .verifyTypeScriptSetup({
dir, dir,
distDir,
intentDirs, intentDirs,
typeCheckPreflight, typeCheckPreflight,
tsconfigPath, tsconfigPath,
...@@ -409,6 +411,7 @@ export default async function build( ...@@ -409,6 +411,7 @@ export default async function build(
.traceAsyncFn(() => .traceAsyncFn(() =>
verifyTypeScriptSetup( verifyTypeScriptSetup(
dir, dir,
config.distDir,
[pagesDir, appDir].filter(Boolean) as string[], [pagesDir, appDir].filter(Boolean) as string[],
!ignoreTypeScriptErrors, !ignoreTypeScriptErrors,
config.typescript.tsconfigPath, config.typescript.tsconfigPath,
......
...@@ -2115,7 +2115,13 @@ export default async function getBaseWebpackConfig( ...@@ -2115,7 +2115,13 @@ export default async function getBaseWebpackConfig(
hasAppDir && hasAppDir &&
!isClient && !isClient &&
!dev && !dev &&
new FlightTypesPlugin({ dir, appDir, dev, isEdgeServer }), new FlightTypesPlugin({
dir,
distDir: config.distDir,
appDir,
dev,
isEdgeServer,
}),
!dev && !dev &&
isClient && isClient &&
!!config.experimental.sri?.algorithm && !!config.experimental.sri?.algorithm &&
......
...@@ -8,6 +8,7 @@ const PLUGIN_NAME = 'FlightTypesPlugin' ...@@ -8,6 +8,7 @@ const PLUGIN_NAME = 'FlightTypesPlugin'
interface Options { interface Options {
dir: string dir: string
distDir: string
appDir: string appDir: string
dev: boolean dev: boolean
isEdgeServer: boolean isEdgeServer: boolean
...@@ -93,19 +94,29 @@ async function collectNamedSlots(layoutPath: string) { ...@@ -93,19 +94,29 @@ async function collectNamedSlots(layoutPath: string) {
export class FlightTypesPlugin { export class FlightTypesPlugin {
dir: string dir: string
distDir: string
appDir: string appDir: string
dev: boolean dev: boolean
isEdgeServer: boolean isEdgeServer: boolean
constructor(options: Options) { constructor(options: Options) {
this.dir = options.dir this.dir = options.dir
this.distDir = options.distDir
this.appDir = options.appDir this.appDir = options.appDir
this.dev = options.dev this.dev = options.dev
this.isEdgeServer = options.isEdgeServer this.isEdgeServer = options.isEdgeServer
} }
apply(compiler: webpack.Compiler) { apply(compiler: webpack.Compiler) {
const assetPrefix = this.dev ? '..' : this.isEdgeServer ? '..' : '../..' // From dist root to project root
const distDirRelative = path.relative(this.distDir + '/..', '.')
// From asset root to dist root
const assetDirRelative = this.dev
? '..'
: this.isEdgeServer
? '..'
: '../..'
const handleModule = async (_mod: webpack.Module, assets: any) => { const handleModule = async (_mod: webpack.Module, assets: any) => {
if (_mod.layer !== WEBPACK_LAYERS.server) return if (_mod.layer !== WEBPACK_LAYERS.server) return
...@@ -127,11 +138,12 @@ export class FlightTypesPlugin { ...@@ -127,11 +138,12 @@ export class FlightTypesPlugin {
) )
const relativeImportPath = path const relativeImportPath = path
.join( .join(
distDirRelative,
path.relative(typePath, ''), path.relative(typePath, ''),
relativePathToRoot.replace(/\.(js|jsx|ts|tsx|mjs)$/, '') relativePathToRoot.replace(/\.(js|jsx|ts|tsx|mjs)$/, '')
) )
.replace(/\\/g, '/') .replace(/\\/g, '/')
const assetPath = assetPrefix + '/' + typePath.replace(/\\/g, '/') const assetPath = assetDirRelative + '/' + typePath.replace(/\\/g, '/')
if (IS_LAYOUT) { if (IS_LAYOUT) {
const slots = await collectNamedSlots(mod.resource) const slots = await collectNamedSlots(mod.resource)
......
...@@ -155,13 +155,14 @@ function getFormattedLayoutAndPageDiagnosticMessageText( ...@@ -155,13 +155,14 @@ function getFormattedLayoutAndPageDiagnosticMessageText(
export async function getFormattedDiagnostic( export async function getFormattedDiagnostic(
ts: typeof import('typescript'), ts: typeof import('typescript'),
baseDir: string, baseDir: string,
distDir: string,
diagnostic: import('typescript').Diagnostic, diagnostic: import('typescript').Diagnostic,
isAppDirEnabled?: boolean isAppDirEnabled?: boolean
): Promise<string> { ): Promise<string> {
// If the error comes from .next/types/, we handle it specially. // If the error comes from .next/types/, we handle it specially.
const isLayoutOrPageError = const isLayoutOrPageError =
isAppDirEnabled && isAppDirEnabled &&
diagnostic.file?.fileName.includes(path.join(baseDir, '.next', 'types')) diagnostic.file?.fileName.startsWith(path.join(baseDir, distDir, 'types'))
let message = '' let message = ''
......
...@@ -20,6 +20,7 @@ export interface TypeCheckResult { ...@@ -20,6 +20,7 @@ export interface TypeCheckResult {
export async function runTypeCheck( export async function runTypeCheck(
ts: typeof import('typescript'), ts: typeof import('typescript'),
baseDir: string, baseDir: string,
distDir: string,
tsConfigPath: string, tsConfigPath: string,
cacheDir?: string, cacheDir?: string,
isAppDirEnabled?: boolean isAppDirEnabled?: boolean
...@@ -97,14 +98,22 @@ export async function runTypeCheck( ...@@ -97,14 +98,22 @@ export async function runTypeCheck(
if (firstError) { if (firstError) {
throw new CompileError( throw new CompileError(
await getFormattedDiagnostic(ts, baseDir, firstError, isAppDirEnabled) await getFormattedDiagnostic(
ts,
baseDir,
distDir,
firstError,
isAppDirEnabled
)
) )
} }
const warnings = await Promise.all( const warnings = await Promise.all(
allDiagnostics allDiagnostics
.filter((d) => d.category === DiagnosticCategory.Warning) .filter((d) => d.category === DiagnosticCategory.Warning)
.map((d) => getFormattedDiagnostic(ts, baseDir, d, isAppDirEnabled)) .map((d) =>
getFormattedDiagnostic(ts, baseDir, distDir, d, isAppDirEnabled)
)
) )
return { return {
hasWarnings: true, hasWarnings: true,
......
...@@ -103,7 +103,8 @@ export async function writeConfigurationDefaults( ...@@ -103,7 +103,8 @@ export async function writeConfigurationDefaults(
ts: typeof import('typescript'), ts: typeof import('typescript'),
tsConfigPath: string, tsConfigPath: string,
isFirstTimeSetup: boolean, isFirstTimeSetup: boolean,
isAppDirEnabled: boolean isAppDirEnabled: boolean,
distDir: string
): Promise<void> { ): Promise<void> {
if (isFirstTimeSetup) { if (isFirstTimeSetup) {
await fs.writeFile(tsConfigPath, '{}' + os.EOL) await fs.writeFile(tsConfigPath, '{}' + os.EOL)
...@@ -162,28 +163,27 @@ export async function writeConfigurationDefaults( ...@@ -162,28 +163,27 @@ export async function writeConfigurationDefaults(
} }
} }
const nextAppTypes = `${distDir}/types/**/*.ts`
if (!('include' in rawConfig)) { if (!('include' in rawConfig)) {
userTsConfig.include = isAppDirEnabled userTsConfig.include = isAppDirEnabled
? ['next-env.d.ts', '.next/types/**/*.ts', '**/*.ts', '**/*.tsx'] ? ['next-env.d.ts', nextAppTypes, '**/*.ts', '**/*.tsx']
: ['next-env.d.ts', '**/*.ts', '**/*.tsx'] : ['next-env.d.ts', '**/*.ts', '**/*.tsx']
suggestedActions.push( suggestedActions.push(
chalk.cyan('include') + chalk.cyan('include') +
' was set to ' + ' was set to ' +
chalk.bold( chalk.bold(
isAppDirEnabled isAppDirEnabled
? `['next-env.d.ts', '.next/types/**/*.ts', '**/*.ts', '**/*.tsx']` ? `['next-env.d.ts', '${nextAppTypes}', '**/*.ts', '**/*.tsx']`
: `['next-env.d.ts', '**/*.ts', '**/*.tsx']` : `['next-env.d.ts', '**/*.ts', '**/*.tsx']`
) )
) )
} else if ( } else if (isAppDirEnabled && !rawConfig.include.includes(nextAppTypes)) {
isAppDirEnabled && userTsConfig.include.push(nextAppTypes)
!rawConfig.include.includes('.next/types/**/*.ts')
) {
userTsConfig.include.push('.next/types/**/*.ts')
suggestedActions.push( suggestedActions.push(
chalk.cyan('include') + chalk.cyan('include') +
' was updated to add ' + ' was updated to add ' +
chalk.bold(`'.next/types/**/*.ts'`) chalk.bold(`'${nextAppTypes}'`)
) )
} }
......
...@@ -39,6 +39,7 @@ const requiredPackages = [ ...@@ -39,6 +39,7 @@ const requiredPackages = [
export async function verifyTypeScriptSetup({ export async function verifyTypeScriptSetup({
dir, dir,
distDir,
cacheDir, cacheDir,
intentDirs, intentDirs,
tsconfigPath, tsconfigPath,
...@@ -47,6 +48,7 @@ export async function verifyTypeScriptSetup({ ...@@ -47,6 +48,7 @@ export async function verifyTypeScriptSetup({
isAppDirEnabled, isAppDirEnabled,
}: { }: {
dir: string dir: string
distDir: string
cacheDir?: string cacheDir?: string
tsconfigPath: string tsconfigPath: string
intentDirs: string[] intentDirs: string[]
...@@ -119,7 +121,8 @@ export async function verifyTypeScriptSetup({ ...@@ -119,7 +121,8 @@ export async function verifyTypeScriptSetup({
ts, ts,
resolvedTsConfigPath, resolvedTsConfigPath,
intent.firstTimeSetup, intent.firstTimeSetup,
isAppDirEnabled isAppDirEnabled,
distDir
) )
// Write out the necessary `next-env.d.ts` file to correctly register // Write out the necessary `next-env.d.ts` file to correctly register
// Next.js' types: // Next.js' types:
...@@ -137,6 +140,7 @@ export async function verifyTypeScriptSetup({ ...@@ -137,6 +140,7 @@ export async function verifyTypeScriptSetup({
result = await runTypeCheck( result = await runTypeCheck(
ts, ts,
dir, dir,
distDir,
resolvedTsConfigPath, resolvedTsConfigPath,
cacheDir, cacheDir,
isAppDirEnabled isAppDirEnabled
......
...@@ -674,6 +674,7 @@ export default class DevServer extends Server { ...@@ -674,6 +674,7 @@ export default class DevServer extends Server {
this.verifyingTypeScript = true this.verifyingTypeScript = true
const verifyResult = await verifyTypeScriptSetup({ const verifyResult = await verifyTypeScriptSetup({
dir: this.dir, dir: this.dir,
distDir: this.nextConfig.distDir,
intentDirs: [this.pagesDir, this.appDir].filter(Boolean) as string[], intentDirs: [this.pagesDir, this.appDir].filter(Boolean) as string[],
typeCheckPreflight: false, typeCheckPreflight: false,
tsconfigPath: this.nextConfig.typescript.tsconfigPath, tsconfigPath: this.nextConfig.typescript.tsconfigPath,
......
module.exports = { module.exports = {
distDir: 'dist/.next',
experimental: { experimental: {
appDir: true, appDir: true,
}, },
......
...@@ -20,6 +20,6 @@ ...@@ -20,6 +20,6 @@
} }
] ]
}, },
"include": ["next-env.d.ts", ".next/types/**/*.ts", "**/*.ts", "**/*.tsx"], "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"] "exclude": ["node_modules"]
} }
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