/
plugin.ts
390 lines (316 loc) · 10.7 KB
/
plugin.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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
import { resolve, dirname, relative } from 'path'
import fs from 'fs-extra'
import os from 'os'
import chalk from 'chalk'
import glob from 'fast-glob'
import { debug } from 'debug'
import { Project } from 'ts-morph'
import { normalizePath } from 'vite'
import { readConfigFile } from 'typescript'
import {
normalizeGlob,
transformDynamicImport,
transformAliasImport,
removePureImport
} from './transform'
import { compileVueCode } from './compile'
import {
isNativeObj,
isPromise,
mergeObjects,
ensureAbsolute,
ensureArray,
runParallel
} from './utils'
import type { Plugin, Alias, Logger } from 'vite'
import type { ts, Diagnostic, SourceFile } from 'ts-morph'
interface TransformWriteFile {
filePath?: string,
content?: string
}
export interface PluginOptions {
include?: string | string[],
exclude?: string | string[],
root?: string,
outputDir?: string,
compilerOptions?: ts.CompilerOptions | null,
tsConfigFilePath?: string,
cleanVueFileName?: boolean,
staticImport?: boolean,
clearPureImport?: boolean,
insertTypesEntry?: boolean,
copyDtsFiles?: boolean,
noEmitOnError?: boolean,
skipDiagnostics?: boolean,
logDiagnostics?: boolean,
afterDiagnostic?: (diagnostics: Diagnostic[]) => void | Promise<void>,
beforeWriteFile?: (filePath: string, content: string) => void | TransformWriteFile,
afterBuild?: () => void | Promise<void>
}
const noneExport = 'export {};\n'
const vueRE = /\.vue$/
const tsRE = /\.tsx?$/
const jsRE = /\.jsx?$/
const dtsRE = /\.d\.tsx?$/
const tjsRE = /\.(t|j)sx?$/
const watchExtensionRE = /\.(vue|(t|j)sx?)$/
// eslint-disable-next-line @typescript-eslint/no-empty-function
const noop = () => {}
const bundleDebug = debug('vite-plugin-dts:bundle')
export function dtsPlugin(options: PluginOptions = {}): Plugin {
const {
tsConfigFilePath = 'tsconfig.json',
cleanVueFileName = false,
staticImport = false,
clearPureImport = true,
insertTypesEntry = false,
noEmitOnError = false,
skipDiagnostics = true,
logDiagnostics = false,
afterDiagnostic = noop,
beforeWriteFile = noop,
afterBuild = noop
} = options
const compilerOptions = options.compilerOptions ?? {}
let root: string
let aliases: Alias[]
let entries: string[]
let logger: Logger
let project: Project
let tsConfigPath: string
let outputDir: string
let isBundle = false
const sourceDtsFiles = new Set<SourceFile>()
let hasJsVue = false
let allowJs = false
return {
name: 'vite:dts',
apply: 'build',
enforce: 'pre',
config(config) {
if (isBundle) return
const aliasOptions = (config.resolve && config.resolve.alias) ?? []
if (isNativeObj(aliasOptions)) {
aliases = Object.entries(aliasOptions).map(([key, value]) => {
return { find: key, replacement: value }
})
} else {
aliases = ensureArray(aliasOptions)
}
},
configResolved(config) {
if (isBundle) return
logger = config.logger
if (!config.build.lib) {
logger.warn(
chalk.yellow(
`\n${chalk.cyan(
'[vite:dts]'
)} You building not a library that may not need to generate declaration files.\n`
)
)
}
root = ensureAbsolute(options.root ?? '', config.root)
tsConfigPath = ensureAbsolute(tsConfigFilePath, root)
outputDir = options.outputDir
? ensureAbsolute(options.outputDir, root)
: ensureAbsolute(config.build.outDir, root)
if (!outputDir) {
logger.error(
chalk.red(
`\n${chalk.cyan(
'[vite:dts]'
)} Can not resolve declaration directory, please check your vite config and plugin options.\n`
)
)
return
}
compilerOptions.rootDir ||= root
project = new Project({
compilerOptions: mergeObjects(compilerOptions, {
noEmitOnError,
outDir: '.',
// #27 declarationDir option will make no declaration file generated
declarationDir: null,
// compile vue setup script will generate expose parameter for setup function
// although user never use it which will get an unexpected unused error
noUnusedParameters: false,
declaration: true,
noEmit: false,
emitDeclarationOnly: true
}),
tsConfigFilePath: tsConfigPath,
skipAddingFilesFromTsConfig: true
})
allowJs = project.getCompilerOptions().allowJs ?? false
},
buildStart(inputOptions) {
if (insertTypesEntry) {
entries = Array.isArray(inputOptions.input)
? inputOptions.input
: Object.values(inputOptions.input)
}
},
transform(code, id) {
if (vueRE.test(id)) {
const { content, ext } = compileVueCode(code)
if (content) {
if (ext === 'js' || ext === 'jsx') hasJsVue = true
project.createSourceFile(`${id}.${ext || 'js'}`, content, { overwrite: true })
}
} else if (!id.includes('.vue?vue') && (tsRE.test(id) || (allowJs && jsRE.test(id)))) {
project.addSourceFileAtPath(id)
}
return null
},
watchChange(id) {
if (watchExtensionRE.test(id)) {
isBundle = false
if (project) {
const sourceFile = project.getSourceFile(normalizePath(id))
sourceFile && project.removeSourceFile(sourceFile)
}
}
},
async closeBundle() {
if (!outputDir || !project || isBundle) return
logger.info(chalk.green(`\n${chalk.cyan('[vite:dts]')} Start generate declaration files...`))
bundleDebug('start')
isBundle = true
sourceDtsFiles.clear()
const startTime = Date.now()
const tsConfig: {
include?: string[],
exclude?: string[]
} = readConfigFile(tsConfigPath, project.getFileSystem().readFileSync).config ?? {}
const include = options.include ?? tsConfig.include
const exclude = options.exclude ?? tsConfig.exclude
bundleDebug('read config')
const includedFileSet = new Set<string>()
if (include && include.length) {
const files = await glob(ensureArray(include).map(normalizeGlob), {
cwd: root,
absolute: true,
ignore: ensureArray(exclude ?? ['node_modules/**']).map(normalizeGlob)
})
files.forEach(file => {
includedFileSet.add(
dtsRE.test(file) ? file : `${tjsRE.test(file) ? file.replace(tjsRE, '') : file}.d.ts`
)
if (dtsRE.test(file)) {
sourceDtsFiles.add(project.addSourceFileAtPath(file))
}
})
if (hasJsVue) {
if (!allowJs) {
logger.warn(
chalk.yellow(
`${chalk.cyan(
'[vite:dts]'
)} Some js files are referenced, but you may not enable the 'allowJs' option.`
)
)
}
project.compilerOptions.set({ allowJs: true })
}
bundleDebug('collect files')
}
project.resolveSourceFileDependencies()
bundleDebug('resolve')
if (!skipDiagnostics) {
const diagnostics = project.getPreEmitDiagnostics()
if (diagnostics?.length && logDiagnostics) {
logger.warn(project.formatDiagnosticsWithColorAndContext(diagnostics))
}
if (typeof afterDiagnostic === 'function') {
const result = afterDiagnostic(diagnostics)
isPromise(result) && (await result)
}
bundleDebug('diagnostics')
}
const service = project.getLanguageService()
const outputFiles = project
.getSourceFiles()
.map(sourceFile =>
service
.getEmitOutput(sourceFile, true)
.getOutputFiles()
.map(outputFile => ({
path: outputFile.getFilePath() as string,
content: outputFile.getText()
}))
)
.flat()
.concat(
Array.from(sourceDtsFiles).map(sourceFile => ({
path: sourceFile.getFilePath(),
content: sourceFile.getFullText()
}))
)
bundleDebug('emit')
await runParallel(os.cpus().length, outputFiles, async outputFile => {
let filePath = outputFile.path
let content = outputFile.content
const isMapFile = filePath.endsWith('.map')
if (
!includedFileSet.has(isMapFile ? filePath.slice(0, -4) : filePath) ||
(clearPureImport && content === noneExport)
)
return
if (!isMapFile && content && content !== noneExport) {
content = clearPureImport ? removePureImport(content) : content
content = transformAliasImport(filePath, content, aliases)
content = staticImport ? transformDynamicImport(content) : content
}
filePath = resolve(
outputDir,
relative(root, cleanVueFileName ? filePath.replace('.vue.d.ts', '.d.ts') : filePath)
)
if (typeof beforeWriteFile === 'function') {
const result = beforeWriteFile(filePath, content)
if (result && isNativeObj(result)) {
filePath = result.filePath ?? filePath
content = result.content ?? content
}
}
await fs.mkdir(dirname(filePath), { recursive: true })
await fs.writeFile(
filePath,
cleanVueFileName ? content.replace(/['"](.+)\.vue['"]/g, '"$1"') : content,
'utf8'
)
})
bundleDebug('output')
if (insertTypesEntry) {
const pkgPath = resolve(root, 'package.json')
const pkg = fs.existsSync(pkgPath) ? JSON.parse(await fs.readFile(pkgPath, 'utf-8')) : {}
const typesPath = pkg.types ? resolve(root, pkg.types) : resolve(outputDir, 'index.d.ts')
if (!fs.existsSync(typesPath)) {
const content =
entries
.map(entry => {
let filePath = normalizePath(
relative(dirname(typesPath), resolve(outputDir, relative(root, entry)))
)
filePath = filePath.replace(tsRE, '')
filePath = /^\.\.?\//.test(filePath) ? filePath : `./${filePath}`
return `export * from '${filePath}'`
})
.join('\n') + '\n'
await fs.writeFile(typesPath, content, 'utf-8')
}
bundleDebug('insert index')
}
if (typeof afterBuild === 'function') {
const result = afterBuild()
isPromise(result) && (await result)
}
bundleDebug('finish')
logger.info(
chalk.green(
`${chalk.cyan('[vite:dts]')} Declaration files built in ${Date.now() - startTime}ms.\n`
)
)
}
}
}