-
Notifications
You must be signed in to change notification settings - Fork 26.3k
/
writeConfigurationDefaults.ts
368 lines (340 loc) · 11.7 KB
/
writeConfigurationDefaults.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
import { promises as fs } from 'fs'
import { bold, cyan, white } from '../picocolors'
import * as CommentJson from 'next/dist/compiled/comment-json'
import semver from 'next/dist/compiled/semver'
import os from 'os'
import type { CompilerOptions } from 'typescript'
import { getTypeScriptConfiguration } from './getTypeScriptConfiguration'
import * as Log from '../../build/output/log'
type DesiredCompilerOptionsShape = {
[K in keyof CompilerOptions]:
| { suggested: any; reason?: string }
| {
parsedValue?: any
parsedValues?: Array<any>
value: any
reason: string
}
}
function getDesiredCompilerOptions(
ts: typeof import('typescript'),
tsOptions?: CompilerOptions
): DesiredCompilerOptionsShape {
const o: DesiredCompilerOptionsShape = {
target: {
suggested: 'ES2017',
reason:
'For top-level `await`. Note: Next.js only polyfills for the esmodules target.',
},
// These are suggested values and will be set when not present in the
// tsconfig.json
lib: { suggested: ['dom', 'dom.iterable', 'esnext'] },
allowJs: { suggested: true },
skipLibCheck: { suggested: true },
strict: { suggested: false },
...(semver.lt(ts.version, '5.0.0')
? { forceConsistentCasingInFileNames: { suggested: true } }
: undefined),
noEmit: { suggested: true },
...(semver.gte(ts.version, '4.4.2')
? { incremental: { suggested: true } }
: undefined),
// These values are required and cannot be changed by the user
// Keep this in sync with the webpack config
// 'parsedValue' matches the output value from ts.parseJsonConfigFileContent()
module: {
parsedValue: ts.ModuleKind.ESNext,
// All of these values work:
parsedValues: [
semver.gte(ts.version, '5.4.0') && (ts.ModuleKind as any).Preserve,
ts.ModuleKind.ES2020,
ts.ModuleKind.ESNext,
ts.ModuleKind.CommonJS,
ts.ModuleKind.AMD,
ts.ModuleKind.NodeNext,
ts.ModuleKind.Node16,
],
value: 'esnext',
reason: 'for dynamic import() support',
},
// TODO: Semver check not needed once Next.js repo uses 5.4.
...(semver.gte(ts.version, '5.4.0') &&
tsOptions?.module === (ts.ModuleKind as any).Preserve
? {
// TypeScript 5.4 introduced `Preserve`. Using `Preserve` implies
// - `moduleResolution` is `Bundler`
// - `esModuleInterop` is `true`
// - `resolveJsonModule` is `true`
// This means that if the user is using Preserve, they don't need these options
}
: {
esModuleInterop: {
value: true,
reason: 'requirement for SWC / babel',
},
moduleResolution: {
// In TypeScript 5.0, `NodeJs` has renamed to `Node10`
parsedValue:
ts.ModuleResolutionKind.Bundler ??
ts.ModuleResolutionKind.NodeNext ??
(ts.ModuleResolutionKind as any).Node10 ??
ts.ModuleResolutionKind.NodeJs,
// All of these values work:
parsedValues: [
(ts.ModuleResolutionKind as any).Node10 ??
ts.ModuleResolutionKind.NodeJs,
// only newer TypeScript versions have this field, it
// will be filtered for new versions of TypeScript
(ts.ModuleResolutionKind as any).Node12,
ts.ModuleResolutionKind.Node16,
ts.ModuleResolutionKind.NodeNext,
ts.ModuleResolutionKind.Bundler,
].filter((val) => typeof val !== 'undefined'),
value: 'node',
reason: 'to match webpack resolution',
},
resolveJsonModule: {
value: true,
reason: 'to match webpack resolution',
},
}),
...(tsOptions?.verbatimModuleSyntax === true
? undefined
: {
isolatedModules: {
value: true,
reason: 'requirement for SWC / Babel',
},
}),
jsx: {
parsedValue: ts.JsxEmit.Preserve,
value: 'preserve',
reason: 'next.js implements its own optimized jsx transform',
},
}
return o
}
export function getRequiredConfiguration(
ts: typeof import('typescript')
): Partial<import('typescript').CompilerOptions> {
const res: Partial<import('typescript').CompilerOptions> = {}
const desiredCompilerOptions = getDesiredCompilerOptions(ts)
for (const optionKey of Object.keys(desiredCompilerOptions)) {
const ev = desiredCompilerOptions[optionKey]
if (!('value' in ev)) {
continue
}
res[optionKey] = ev.parsedValue ?? ev.value
}
return res
}
export async function writeConfigurationDefaults(
ts: typeof import('typescript'),
tsConfigPath: string,
isFirstTimeSetup: boolean,
hasAppDir: boolean,
distDir: string,
hasPagesDir: boolean
): Promise<void> {
if (isFirstTimeSetup) {
await fs.writeFile(tsConfigPath, '{}' + os.EOL)
}
const { options: tsOptions, raw: rawConfig } =
await getTypeScriptConfiguration(ts, tsConfigPath, true)
const userTsConfigContent = await fs.readFile(tsConfigPath, {
encoding: 'utf8',
})
const userTsConfig = CommentJson.parse(userTsConfigContent)
if (userTsConfig.compilerOptions == null && !('extends' in rawConfig)) {
userTsConfig.compilerOptions = {}
isFirstTimeSetup = true
}
const desiredCompilerOptions = getDesiredCompilerOptions(ts, tsOptions)
const suggestedActions: string[] = []
const requiredActions: string[] = []
for (const optionKey of Object.keys(desiredCompilerOptions)) {
const check = desiredCompilerOptions[optionKey]
if ('suggested' in check) {
if (!(optionKey in tsOptions)) {
if (!userTsConfig.compilerOptions) {
userTsConfig.compilerOptions = {}
}
userTsConfig.compilerOptions[optionKey] = check.suggested
suggestedActions.push(
cyan(optionKey) +
' was set to ' +
bold(check.suggested) +
(check.reason ? ` (${check.reason})` : '')
)
}
} else if ('value' in check) {
const ev = tsOptions[optionKey]
if (
!('parsedValues' in check
? check.parsedValues?.includes(ev)
: 'parsedValue' in check
? check.parsedValue === ev
: check.value === ev)
) {
if (!userTsConfig.compilerOptions) {
userTsConfig.compilerOptions = {}
}
userTsConfig.compilerOptions[optionKey] = check.value
requiredActions.push(
cyan(optionKey) +
' was set to ' +
bold(check.value) +
` (${check.reason})`
)
}
} else {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const _: never = check
}
}
const nextAppTypes = `${distDir}/types/**/*.ts`
if (!('include' in rawConfig)) {
userTsConfig.include = hasAppDir
? ['next-env.d.ts', nextAppTypes, '**/*.ts', '**/*.tsx']
: ['next-env.d.ts', '**/*.ts', '**/*.tsx']
suggestedActions.push(
cyan('include') +
' was set to ' +
bold(
hasAppDir
? `['next-env.d.ts', '${nextAppTypes}', '**/*.ts', '**/*.tsx']`
: `['next-env.d.ts', '**/*.ts', '**/*.tsx']`
)
)
} else if (hasAppDir && !rawConfig.include.includes(nextAppTypes)) {
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 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(', ')}]`
)
)
} else {
userTsConfig.include.push(nextAppTypes)
suggestedActions.push(
cyan('include') + ' was updated to add ' + bold(`'${nextAppTypes}'`)
)
}
}
// Enable the Next.js typescript plugin.
if (hasAppDir) {
// Check if the config or the resolved config has the plugin already.
const plugins = [
...(Array.isArray(tsOptions.plugins) ? tsOptions.plugins : []),
...(userTsConfig.compilerOptions &&
Array.isArray(userTsConfig.compilerOptions.plugins)
? userTsConfig.compilerOptions.plugins
: []),
]
const hasNextPlugin = plugins.some(
({ name }: { name: string }) => name === 'next'
)
// If the TS config extends on another config, we can't add the `plugin` field
// because that will override the parent config's plugins.
// Instead we have to show a message to the user to add the plugin manually.
if (
!userTsConfig.compilerOptions ||
(plugins.length &&
!hasNextPlugin &&
'extends' in rawConfig &&
(!rawConfig.compilerOptions || !rawConfig.compilerOptions.plugins))
) {
Log.info(
`\nYour ${bold(
'tsconfig.json'
)} extends another configuration, which means we cannot add the Next.js TypeScript plugin automatically. To improve your development experience, we recommend adding the Next.js plugin (\`${cyan(
'"plugins": [{ "name": "next" }]'
)}\`) manually to your TypeScript configuration. Learn more: https://nextjs.org/docs/app/building-your-application/configuring/typescript#the-typescript-plugin\n`
)
} else if (!hasNextPlugin) {
if (!('plugins' in userTsConfig.compilerOptions)) {
userTsConfig.compilerOptions.plugins = []
}
userTsConfig.compilerOptions.plugins.push({ name: 'next' })
suggestedActions.push(
cyan('plugins') + ' was updated to add ' + bold(`{ name: 'next' }`)
)
}
// If `strict` is set to `false` and `strictNullChecks` is set to `false`,
// then set `strictNullChecks` to `true`.
if (
hasPagesDir &&
hasAppDir &&
!tsOptions.strict &&
!('strictNullChecks' in tsOptions)
) {
userTsConfig.compilerOptions.strictNullChecks = true
suggestedActions.push(
cyan('strictNullChecks') + ' was set to ' + bold(`true`)
)
}
}
if (!('exclude' in rawConfig)) {
userTsConfig.exclude = ['node_modules']
suggestedActions.push(
cyan('exclude') + ' was set to ' + bold(`['node_modules']`)
)
}
if (suggestedActions.length < 1 && requiredActions.length < 1) {
return
}
await fs.writeFile(
tsConfigPath,
CommentJson.stringify(userTsConfig, null, 2) + os.EOL
)
Log.info('')
if (isFirstTimeSetup) {
Log.info(
`We detected TypeScript in your project and created a ${cyan(
'tsconfig.json'
)} file for you.`
)
return
}
Log.info(
`We detected TypeScript in your project and reconfigured your ${cyan(
'tsconfig.json'
)} file for you.${
userTsConfig.compilerOptions?.strict
? ''
: ` Strict-mode is set to ${cyan('false')} by default.`
}`
)
if (suggestedActions.length) {
Log.info(
`The following suggested values were added to your ${cyan(
'tsconfig.json'
)}. These values ${cyan('can be changed')} to fit your project's needs:\n`
)
suggestedActions.forEach((action) => Log.info(`\t- ${action}`))
Log.info('')
}
if (requiredActions.length) {
Log.info(
`The following ${white('mandatory changes')} were made to your ${cyan(
'tsconfig.json'
)}:\n`
)
requiredActions.forEach((action) => Log.info(`\t- ${action}`))
Log.info('')
}
}