/
build.ts
584 lines (549 loc) · 16.9 KB
/
build.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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
import fs from 'fs'
import path from 'path'
import chalk from 'chalk'
import { resolveConfig, InlineConfig, ResolvedConfig } from './config'
import Rollup, {
Plugin,
RollupBuild,
RollupOptions,
RollupWarning,
WarningHandler,
OutputOptions,
RollupOutput,
ExternalOption,
GetManualChunk,
GetModuleInfo
} from 'rollup'
import { buildReporterPlugin } from './plugins/reporter'
import { buildDefinePlugin } from './plugins/define'
import { buildHtmlPlugin } from './plugins/html'
import { buildEsbuildPlugin } from './plugins/esbuild'
import { terserPlugin } from './plugins/terser'
import { Terser } from 'types/terser'
import { copyDir, emptyDir, lookupFile, normalizePath } from './utils'
import { manifestPlugin } from './plugins/manifest'
import commonjsPlugin from '@rollup/plugin-commonjs'
import { RollupCommonJSOptions } from 'types/commonjs'
import dynamicImportVars from '@rollup/plugin-dynamic-import-vars'
import { Logger } from './logger'
import { TransformOptions } from 'esbuild'
import { CleanCSS } from 'types/clean-css'
import { dataURIPlugin } from './plugins/dataUri'
import { buildImportAnalysisPlugin } from './plugins/importAnaysisBuild'
import { resolveSSRExternal } from './ssr/ssrExternal'
import { ssrManifestPlugin } from './ssr/ssrManifestPlugin'
import { isCSSRequest } from './plugins/css'
export interface BuildOptions {
/**
* Base public path when served in production.
* @deprecated `base` is now a root-level config option.
*/
base?: string
/**
* Compatibility transform target. The transform is performed with esbuild
* and the lowest supported target is es2015/es6. Note this only handles
* syntax transformation and does not cover polyfills (except for dynamic
* import)
*
* Default: 'modules' - Similar to `@babel/preset-env`'s targets.esmodules,
* transpile targeting browsers that natively support es module imports. Also
* injects a light-weight dynamic import polyfill.
* https://caniuse.com/es6-module
*
* Another special value is 'esnext' - which only performs minimal trasnpiling
* (for minification compat) and assumes native dynamic imports support.
*
* For custom targets, see https://esbuild.github.io/api/#target and
* https://esbuild.github.io/content-types/#javascript for more details.
*/
target?: 'modules' | TransformOptions['target'] | false
/**
* Whether to inject dynamic import polyfill. Defaults to `true`, unless
* `target` is `'esnext'`.
* Note: does not apply to library mode.
*/
polyfillDynamicImport?: boolean
/**
* Directory relative from `root` where build output will be placed. If the
* directory exists, it will be removed before the build.
* @default 'dist'
*/
outDir?: string
/**
* Directory relative from `outDir` where the built js/css/image assets will
* be placed.
* @default 'assets'
*/
assetsDir?: string
/**
* Static asset files smaller than this number (in bytes) will be inlined as
* base64 strings. Default limit is `4096` (4kb). Set to `0` to disable.
* @default 4096
*/
assetsInlineLimit?: number
/**
* Whether to code-split CSS. When enabled, CSS in async chunks will be
* inlined as strings in the chunk and inserted via dynamically created
* style tags when the chunk is loaded.
* @default true
*/
cssCodeSplit?: boolean
/**
* Whether to generate sourcemap
* @default false
*/
sourcemap?: boolean | 'inline'
/**
* Set to `false` to disable minification, or specify the minifier to use.
* Available options are 'terser' or 'esbuild'.
* @default 'terser'
*/
minify?: boolean | 'terser' | 'esbuild'
/**
* Options for terser
* https://terser.org/docs/api-reference#minify-options
*/
terserOptions?: Terser.MinifyOptions
/**
* Options for clean-css
* https://github.com/jakubpawlowicz/clean-css#constructor-options
*/
cleanCssOptions?: CleanCSS.Options
/**
* Will be merged with internal rollup options.
* https://rollupjs.org/guide/en/#big-list-of-options
*/
rollupOptions?: RollupOptions
/**
* Options to pass on to `@rollup/plugin-commonjs`
*/
commonjsOptions?: RollupCommonJSOptions
/**
* Whether to write bundle to disk
* @default true
*/
write?: boolean
/**
* Empty outDir on write.
* @default true when outDir is a sub directory of project root
*/
emptyOutDir?: boolean | null
/**
* Whether to emit a manifest.json under assets dir to map hash-less filenames
* to their hashed versions. Useful when you want to generate your own HTML
* instead of using the one generated by Vite.
*
* Example:
*
* ```json
* {
* "main.js": { "file": "main.68fe3fad.js" },
* "style.css": { "file": "style.e6b63442.css" }
* }
* ```
* @default false
*/
manifest?: boolean
/**
* Build in library mode. The value should be the global name of the lib in
* UMD mode. This will produce esm + cjs + umd bundle formats with default
* configurations that are suitable for distributing libraries.
*/
lib?: LibraryOptions | false
/**
* Produce SSR oriented build. Note this requires specifying SSR entry via
* `rollupOptions.input`.
*/
ssr?: boolean | string
/**
* Generate SSR manifest for determining style links and asset preload
* directives in production.
*/
ssrManifest?: boolean
}
export interface LibraryOptions {
entry: string
name?: string
formats?: LibraryFormats[]
}
export type LibraryFormats = 'es' | 'cjs' | 'umd' | 'iife'
export type ResolvedBuildOptions = Required<Omit<BuildOptions, 'base'>>
export function resolveBuildOptions(raw?: BuildOptions): ResolvedBuildOptions {
const resolved: ResolvedBuildOptions = {
target: 'modules',
polyfillDynamicImport: raw?.target !== 'esnext' && !raw?.lib,
outDir: 'dist',
assetsDir: 'assets',
assetsInlineLimit: 4096,
cssCodeSplit: !raw?.lib,
sourcemap: false,
rollupOptions: {},
commonjsOptions: {
include: [/node_modules/],
extensions: ['.js', '.cjs'],
...raw?.commonjsOptions
},
minify: raw?.ssr ? false : 'terser',
terserOptions: {},
cleanCssOptions: {},
write: true,
emptyOutDir: null,
manifest: false,
lib: false,
ssr: false,
ssrManifest: false,
...raw
}
// handle special build targets
if (resolved.target === 'modules') {
// https://caniuse.com/es6-module
resolved.target = ['es2019', 'edge16', 'firefox60', 'chrome61', 'safari11']
} else if (resolved.target === 'esnext' && resolved.minify !== 'esbuild') {
// esnext + terser: limit to es2019 so it can be minified by terser
resolved.target = 'es2019'
}
// normalize false string into actual false
if ((resolved.minify as any) === 'false') {
resolved.minify = false
}
return resolved
}
export function resolveBuildPlugins(
config: ResolvedConfig
): { pre: Plugin[]; post: Plugin[] } {
const options = config.build
return {
pre: [
buildHtmlPlugin(config),
commonjsPlugin(options.commonjsOptions),
dataURIPlugin(),
buildDefinePlugin(config),
dynamicImportVars({
warnOnError: true,
exclude: [/node_modules/]
}),
...(options.rollupOptions.plugins || [])
],
post: [
buildImportAnalysisPlugin(config),
buildEsbuildPlugin(config),
...(options.minify && options.minify !== 'esbuild'
? [terserPlugin(options.terserOptions)]
: []),
...(options.manifest ? [manifestPlugin(config)] : []),
...(options.ssrManifest ? [ssrManifestPlugin(config)] : []),
...(!config.logLevel || config.logLevel === 'info'
? [buildReporterPlugin(config)]
: [])
]
}
}
/**
* Track parallel build calls and only stop the esbuild service when all
* builds are done. (#1098)
*/
let parallelCallCounts = 0
// we use a separate counter to track since the call may error before the
// bundle is even pushed.
const paralellBuilds: RollupBuild[] = []
/**
* Bundles the app for production.
* Returns a Promise containing the build result.
*/
export async function build(
inlineConfig: InlineConfig = {}
): Promise<RollupOutput | RollupOutput[]> {
parallelCallCounts++
try {
return await doBuild(inlineConfig)
} finally {
parallelCallCounts--
if (parallelCallCounts <= 0) {
paralellBuilds.forEach((bundle) => bundle.close())
paralellBuilds.length = 0
}
}
}
async function doBuild(
inlineConfig: InlineConfig = {}
): Promise<RollupOutput | RollupOutput[]> {
const config = await resolveConfig(inlineConfig, 'build', 'production')
const options = config.build
const ssr = !!options.ssr
const libOptions = options.lib
config.logger.info(
chalk.cyan(`building ${ssr ? `SSR bundle ` : ``}for ${config.mode}...`)
)
const resolve = (p: string) => path.resolve(config.root, p)
const input = libOptions
? resolve(libOptions.entry)
: typeof options.ssr === 'string'
? resolve(options.ssr)
: options.rollupOptions?.input || resolve('index.html')
if (ssr && typeof input === 'string' && input.endsWith('.html')) {
throw new Error(
`rollupOptions.input should not be an html file when building for SSR. ` +
`Please specify a dedicated SSR entry.`
)
}
const outDir = resolve(options.outDir)
const publicDir = resolve('public')
// inject ssr arg to plugin load/transform hooks
const plugins = (ssr
? config.plugins.map((p) => injectSsrFlagToHooks(p))
: config.plugins) as Plugin[]
// inject ssrExternal if present
const userExternal = options.rollupOptions?.external
const external = ssr
? resolveExternal(resolveSSRExternal(config), userExternal)
: userExternal
const rollup = require('rollup') as typeof Rollup
try {
const bundle = await rollup.rollup({
input,
preserveEntrySignatures: ssr
? 'allow-extension'
: libOptions
? 'strict'
: false,
...options.rollupOptions,
plugins,
external,
onwarn(warning, warn) {
onRollupWarning(warning, warn, config)
}
})
paralellBuilds.push(bundle)
const pkgName =
libOptions &&
JSON.parse(lookupFile(config.root, ['package.json']) || `{}`).name
const generate = (output: OutputOptions = {}) => {
return bundle[options.write ? 'write' : 'generate']({
dir: outDir,
format: ssr ? 'cjs' : 'es',
exports: ssr ? 'named' : 'auto',
sourcemap: options.sourcemap,
name: libOptions ? libOptions.name : undefined,
entryFileNames: ssr
? `[name].js`
: libOptions
? `${pkgName}.${output.format || `es`}.js`
: path.posix.join(options.assetsDir, `[name].[hash].js`),
chunkFileNames: libOptions
? `[name].js`
: path.posix.join(options.assetsDir, `[name].[hash].js`),
assetFileNames: libOptions
? `[name].[ext]`
: path.posix.join(options.assetsDir, `[name].[hash].[ext]`),
// #764 add `Symbol.toStringTag` when build es module into cjs chunk
// #1048 add `Symbol.toStringTag` for module default export
namespaceToStringTag: true,
inlineDynamicImports: ssr && typeof input === 'string',
manualChunks:
!ssr &&
!libOptions &&
output?.format !== 'umd' &&
output?.format !== 'iife'
? createMoveToVendorChunkFn(config)
: undefined,
...output
})
}
if (options.write) {
// warn if outDir is outside of root
if (fs.existsSync(outDir)) {
const inferEmpty = options.emptyOutDir === null
if (
options.emptyOutDir ||
(inferEmpty && normalizePath(outDir).startsWith(config.root + '/'))
) {
emptyDir(outDir)
} else if (inferEmpty) {
config.logger.warn(
chalk.yellow(
`\n${chalk.bold(`(!)`)} outDir ${chalk.white.dim(
outDir
)} is not inside project root and will not be emptied.\n` +
`Use --emptyOutDir to override.\n`
)
)
}
}
if (fs.existsSync(publicDir)) {
copyDir(publicDir, outDir)
}
}
// resolve lib mode outputs
const outputs = resolveBuildOutputs(
options.rollupOptions?.output,
libOptions,
config.logger
)
if (Array.isArray(outputs)) {
const res = []
for (const output of outputs) {
res.push(await generate(output))
}
return res
} else {
return generate(outputs)
}
} catch (e) {
config.logger.error(
chalk.red(`${e.plugin ? `[${e.plugin}] ` : ``}${e.message}`)
)
if (e.id) {
const loc = e.loc ? `:${e.loc.line}:${e.loc.column}` : ``
config.logger.error(`file: ${chalk.cyan(`${e.id}${loc}`)}`)
}
if (e.frame) {
config.logger.error(chalk.yellow(e.frame))
}
throw e
}
}
function createMoveToVendorChunkFn(config: ResolvedConfig): GetManualChunk {
const cache = new Map<string, boolean>()
return (id, { getModuleInfo }) => {
if (
id.includes('node_modules') &&
!isCSSRequest(id) &&
!hasDynamicImporter(id, getModuleInfo, cache)
) {
return 'vendor'
}
}
}
function hasDynamicImporter(
id: string,
getModuleInfo: GetModuleInfo,
cache: Map<string, boolean>,
importStack: string[] = []
): boolean {
if (cache.has(id)) {
return cache.get(id) as boolean
}
if (importStack.includes(id)) {
// circular deps!
cache.set(id, false)
return false
}
const mod = getModuleInfo(id)
if (!mod) {
cache.set(id, false)
return false
}
if (mod.dynamicImporters.length) {
cache.set(id, true)
return true
}
const someImporterHas = mod.importers.some((importer) =>
hasDynamicImporter(importer, getModuleInfo, cache, importStack.concat(id))
)
cache.set(id, someImporterHas)
return someImporterHas
}
function resolveBuildOutputs(
outputs: OutputOptions | OutputOptions[] | undefined,
libOptions: LibraryOptions | false,
logger: Logger
): OutputOptions | OutputOptions[] | undefined {
if (libOptions) {
const formats = libOptions.formats || ['es', 'umd']
if (
(formats.includes('umd') || formats.includes('iife')) &&
!libOptions.name
) {
throw new Error(
`Option "build.lib.name" is required when output formats ` +
`include "umd" or "iife".`
)
}
if (!outputs) {
return formats.map((format) => ({ format }))
} else if (!Array.isArray(outputs)) {
return formats.map((format) => ({ ...outputs, format }))
} else if (libOptions.formats) {
// user explicitly specifying own output array
logger.warn(
chalk.yellow(
`"build.lib.formats" will be ignored because ` +
`"build.rollupOptions.output" is already an array format`
)
)
}
}
return outputs
}
const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`]
const dynamicImportWarningIgnoreList = [
`Unsupported expression`,
`statically analyzed`
]
export function onRollupWarning(
warning: RollupWarning,
warn: WarningHandler,
config: ResolvedConfig
) {
if (warning.code === 'UNRESOLVED_IMPORT') {
const id = warning.source
const importer = warning.importer
// throw unless it's commonjs external...
if (!importer || !/\?commonjs-external$/.test(importer)) {
throw new Error(
`[vite]: Rollup failed to resolve import "${id}" from "${importer}".\n` +
`This is most likely unintended because it can break your application at runtime.\n` +
`If you do want to externalize this module explicitly add it to\n` +
`\`build.rollupOptions.external\``
)
}
}
if (
warning.plugin === 'rollup-plugin-dynamic-import-variables' &&
dynamicImportWarningIgnoreList.some((msg) => warning.message.includes(msg))
) {
return
}
if (!warningIgnoreList.includes(warning.code!)) {
const userOnWarn = config.build.rollupOptions?.onwarn
if (userOnWarn) {
userOnWarn(warning, warn)
} else if (warning.code === 'PLUGIN_WARNING') {
config.logger.warn(
`${chalk.bold.yellow(`[plugin:${warning.plugin}]`)} ${chalk.yellow(
warning.message
)}`
)
} else {
warn(warning)
}
}
}
export function resolveExternal(
existing: string[],
user: ExternalOption | undefined
): ExternalOption {
if (!user) return existing
if (typeof user !== 'function') {
return existing.concat(user as any[])
}
return ((id, parentId, isResolved) => {
if (existing.includes(id)) return true
return user(id, parentId, isResolved)
}) as ExternalOption
}
function injectSsrFlagToHooks(p: Plugin): Plugin {
const { resolveId, load, transform } = p
return {
...p,
resolveId: wrapSsrHook(resolveId),
load: wrapSsrHook(load),
transform: wrapSsrHook(transform)
}
}
function wrapSsrHook(fn: Function | undefined) {
if (!fn) return
return function (this: any, ...args: any[]) {
return fn.call(this, ...args, true)
}
}