/
writeConfigurationDefaults.ts
228 lines (206 loc) · 6.49 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
import { promises as fs } from 'fs'
import chalk from 'next/dist/compiled/chalk'
import * as CommentJson from 'next/dist/compiled/comment-json'
import semver from 'next/dist/compiled/semver'
import os from 'os'
import { getTypeScriptConfiguration } from './getTypeScriptConfiguration'
type DesiredCompilerOptionsShape = {
[key: string]:
| { suggested: any }
| {
parsedValue?: any
parsedValues?: Array<any>
value: any
reason: string
}
}
function getDesiredCompilerOptions(
ts: typeof import('typescript')
): DesiredCompilerOptionsShape {
const o: DesiredCompilerOptionsShape = {
// These are suggested values and will be set when not present in the
// tsconfig.json
target: { suggested: 'es5' },
lib: { suggested: ['dom', 'dom.iterable', 'esnext'] },
allowJs: { suggested: true },
skipLibCheck: { suggested: true },
strict: { suggested: false },
forceConsistentCasingInFileNames: { suggested: true },
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()
esModuleInterop: {
value: true,
reason: 'requirement for SWC / babel',
},
module: {
parsedValue: ts.ModuleKind.ESNext,
// All of these values work:
parsedValues: [
ts.ModuleKind.ES2020,
ts.ModuleKind.ESNext,
ts.ModuleKind.CommonJS,
ts.ModuleKind.AMD,
],
value: 'esnext',
reason: 'for dynamic import() support',
},
moduleResolution: {
parsedValue: ts.ModuleResolutionKind.NodeJs,
// All of these values work:
parsedValues: [
ts.ModuleResolutionKind.NodeJs,
ts.ModuleResolutionKind.Node12,
ts.ModuleResolutionKind.NodeNext,
],
value: 'node',
reason: 'to match webpack resolution',
},
resolveJsonModule: { value: true, reason: 'to match webpack resolution' },
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
): Promise<void> {
if (isFirstTimeSetup) {
await fs.writeFile(tsConfigPath, '{}' + os.EOL)
}
const desiredCompilerOptions = getDesiredCompilerOptions(ts)
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 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(
chalk.cyan(optionKey) + ' was set to ' + chalk.bold(check.suggested)
)
}
} 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(
chalk.cyan(optionKey) +
' was set to ' +
chalk.bold(check.value) +
` (${check.reason})`
)
}
} else {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const _: never = check
}
}
if (!('include' in rawConfig)) {
userTsConfig.include = ['next-env.d.ts', '**/*.ts', '**/*.tsx']
suggestedActions.push(
chalk.cyan('include') +
' was set to ' +
chalk.bold(`['next-env.d.ts', '**/*.ts', '**/*.tsx']`)
)
}
if (!('exclude' in rawConfig)) {
userTsConfig.exclude = ['node_modules']
suggestedActions.push(
chalk.cyan('exclude') + ' was set to ' + chalk.bold(`['node_modules']`)
)
}
if (suggestedActions.length < 1 && requiredActions.length < 1) {
return
}
await fs.writeFile(
tsConfigPath,
CommentJson.stringify(userTsConfig, null, 2) + os.EOL
)
if (isFirstTimeSetup) {
console.log(
chalk.green(
`We detected TypeScript in your project and created a ${chalk.bold(
'tsconfig.json'
)} file for you.`
) + '\n'
)
return
}
console.log(
chalk.green(
`We detected TypeScript in your project and reconfigured your ${chalk.bold(
'tsconfig.json'
)} file for you. Strict-mode is set to ${chalk.bold('false')} by default.`
) + '\n'
)
if (suggestedActions.length) {
console.log(
`The following suggested values were added to your ${chalk.cyan(
'tsconfig.json'
)}. These values ${chalk.bold(
'can be changed'
)} to fit your project's needs:\n`
)
suggestedActions.forEach((action) => console.log(`\t- ${action}`))
console.log('')
}
if (requiredActions.length) {
console.log(
`The following ${chalk.bold(
'mandatory changes'
)} were made to your ${chalk.cyan('tsconfig.json')}:\n`
)
requiredActions.forEach((action) => console.log(`\t- ${action}`))
console.log('')
}
}