/
writeVscodeConfigurations.ts
60 lines (53 loc) · 1.69 KB
/
writeVscodeConfigurations.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
import path from 'path'
import isError from '../is-error'
import { promises as fs } from 'fs'
import * as Log from '../../build/output/log'
import * as CommentJson from 'next/dist/compiled/comment-json'
// Write .vscode settings to enable Next.js typescript plugin.
export async function writeVscodeConfigurations(
baseDir: string,
tsPath: string
): Promise<void> {
try {
const vscodeSettings = path.join(baseDir, '.vscode', 'settings.json')
let settings: any = {}
let configExisted = false
let currentContent: string = ''
try {
currentContent = await fs.readFile(vscodeSettings, 'utf8')
settings = CommentJson.parse(currentContent)
configExisted = true
} catch (err) {
if (isError(err) && err.code !== 'ENOENT') {
throw err
}
}
const libPath = path.relative(baseDir, path.dirname(tsPath))
if (
settings['typescript.tsdk'] === libPath &&
settings['typescript.enablePromptUseWorkspaceTsdk']
) {
return
}
settings['typescript.tsdk'] = libPath
settings['typescript.enablePromptUseWorkspaceTsdk'] = true
const content = CommentJson.stringify(settings, null, 2)
const vscodeFolder = path.join(baseDir, '.vscode')
try {
await fs.lstat(vscodeFolder)
} catch (e) {
await fs.mkdir(vscodeFolder, { recursive: true })
}
await fs.writeFile(vscodeSettings, content)
Log.info(
`VS Code settings.json has been ${
configExisted ? 'updated' : 'created'
} for Next.js' automatic app types, this file can be added to .gitignore if desired`
)
} catch (err) {
Log.error(
`Failed to apply custom vscode config for Next.js' app types`,
err
)
}
}