|
| 1 | +import os from 'os' |
| 2 | +import path from 'path' |
| 3 | +import { promises as fs } from 'fs' |
| 4 | + |
| 5 | +export async function writeAppTypeDeclarations({ |
| 6 | + baseDir, |
| 7 | + distDir, |
| 8 | + imageImportsEnabled, |
| 9 | + hasPagesDir, |
| 10 | + hasAppDir, |
| 11 | +}: { |
| 12 | + baseDir: string |
| 13 | + distDir: string |
| 14 | + imageImportsEnabled: boolean |
| 15 | + hasPagesDir: boolean |
| 16 | + hasAppDir: boolean |
| 17 | +}): Promise<void> { |
| 18 | + // Reference `next` types |
| 19 | + const appTypeDeclarations = path.join(baseDir, 'next-env.d.ts') |
| 20 | + |
| 21 | + // Defaults EOL to system default |
| 22 | + let eol = os.EOL |
| 23 | + let currentContent: string | undefined |
| 24 | + |
| 25 | + try { |
| 26 | + currentContent = await fs.readFile(appTypeDeclarations, 'utf8') |
| 27 | + // If file already exists then preserve its line ending |
| 28 | + const lf = currentContent.indexOf('\n', /* skip first so we can lf - 1 */ 1) |
| 29 | + |
| 30 | + if (lf !== -1) { |
| 31 | + if (currentContent[lf - 1] === '\r') { |
| 32 | + eol = '\r\n' |
| 33 | + } else { |
| 34 | + eol = '\n' |
| 35 | + } |
| 36 | + } |
| 37 | + } catch {} |
| 38 | + |
| 39 | + /** |
| 40 | + * "Triple-slash directives" used to create typings files for Next.js projects |
| 41 | + * using Typescript . |
| 42 | + * |
| 43 | + * @see https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html |
| 44 | + */ |
| 45 | + const directives: string[] = [ |
| 46 | + // Include the core Next.js typings. |
| 47 | + '/// <reference types="next" />', |
| 48 | + ] |
| 49 | + |
| 50 | + if (imageImportsEnabled) { |
| 51 | + directives.push('/// <reference types="next/image-types/global" />') |
| 52 | + } |
| 53 | + |
| 54 | + if (hasAppDir && hasPagesDir) { |
| 55 | + directives.push( |
| 56 | + '/// <reference types="next/navigation-types/compat/navigation" />' |
| 57 | + ) |
| 58 | + } |
| 59 | + |
| 60 | + const routeTypesPath = path.posix.join( |
| 61 | + distDir.replaceAll(path.win32.sep, path.posix.sep), |
| 62 | + 'types/routes.d.ts' |
| 63 | + ) |
| 64 | + |
| 65 | + // Use ESM import instead of triple-slash reference for better ESLint compatibility |
| 66 | + directives.push(`import "./${routeTypesPath}";`) |
| 67 | + |
| 68 | + // Push the notice in. |
| 69 | + directives.push( |
| 70 | + '', |
| 71 | + '// NOTE: This file should not be edited', |
| 72 | + `// see https://nextjs.org/docs/${hasAppDir ? 'app' : 'pages'}/api-reference/config/typescript for more information.` |
| 73 | + ) |
| 74 | + |
| 75 | + const content = directives.join(eol) + eol |
| 76 | + |
| 77 | + // Avoids an un-necessary write on read-only fs |
| 78 | + if (currentContent === content) { |
| 79 | + return |
| 80 | + } |
| 81 | + await fs.writeFile(appTypeDeclarations, content) |
| 82 | +} |
0 commit comments