-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
index.ts
586 lines (549 loc) · 16.8 KB
/
index.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
585
586
import path from 'path'
import fs from 'fs-extra'
import chalk from 'chalk'
import { Ora } from 'ora'
import { resolveFrom, lookupFile } from '../utils'
import {
rollup as Rollup,
RollupOutput,
ExternalOption,
Plugin,
InputOptions
} from 'rollup'
import {
createResolver,
supportedExts,
mainFields,
InternalResolver
} from '../resolver'
import { createBuildResolvePlugin } from './buildPluginResolve'
import { createBuildHtmlPlugin } from './buildPluginHtml'
import { createBuildCssPlugin } from './buildPluginCss'
import { createBuildAssetPlugin } from './buildPluginAsset'
import {
createEsbuildPlugin,
createEsbuildRenderChunkPlugin
} from './buildPluginEsbuild'
import { createReplacePlugin } from './buildPluginReplace'
import { stopService } from '../esbuildService'
import { BuildConfig, defaultDefines } from '../config'
import { createBuildJsTransformPlugin } from '../transform'
import hash_sum from 'hash-sum'
import { resolvePostcssOptions, isCSSRequest } from '../utils/cssUtils'
import { createBuildWasmPlugin } from './buildPluginWasm'
export interface BuildResult {
html: string
assets: RollupOutput['output']
}
const enum WriteType {
JS,
CSS,
ASSET,
HTML,
SOURCE_MAP
}
const writeColors = {
[WriteType.JS]: chalk.cyan,
[WriteType.CSS]: chalk.magenta,
[WriteType.ASSET]: chalk.green,
[WriteType.HTML]: chalk.blue,
[WriteType.SOURCE_MAP]: chalk.gray
}
const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`]
const dynamicImportWarningIgnoreList = [
`Unsupported expression`,
`statically analyzed`
]
const isBuiltin = require('isbuiltin')
export function onRollupWarning(
spinner: Ora | undefined,
options: BuildConfig['optimizeDeps']
): InputOptions['onwarn'] {
return (warning, warn) => {
if (warning.code === 'UNRESOLVED_IMPORT') {
let message: string
const id = warning.source
const importer = warning.importer
if (isBuiltin(id)) {
let importingDep
if (importer) {
const pkg = JSON.parse(lookupFile(importer, ['package.json']) || `{}`)
if (pkg.name) {
importingDep = pkg.name
}
}
const allowList = options && options.allowNodeBuiltins
if (importingDep && allowList && allowList.includes(importingDep)) {
return
}
const dep = importingDep
? `Dependency ${chalk.yellow(importingDep)}`
: `A dependency`
message =
`${dep} is attempting to import Node built-in module ${chalk.yellow(
id
)}.\n` +
`This will not work in a browser environment.\n` +
`Imported by: ${chalk.gray(importer)}`
} else {
message =
`[vite]: Rollup failed to resolve import "${warning.source}" from "${warning.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` +
`\`rollupInputOptions.external\``
}
if (spinner) {
spinner.stop()
}
throw new Error(message)
}
if (
warning.plugin === 'rollup-plugin-dynamic-import-variables' &&
dynamicImportWarningIgnoreList.some((msg) =>
warning.message.includes(msg)
)
) {
return
}
if (!warningIgnoreList.includes(warning.code!)) {
// ora would swallow the console.warn if we let it keep running
// https://github.com/sindresorhus/ora/issues/90
if (spinner) {
spinner.stop()
}
warn(warning)
if (spinner) {
spinner.start()
}
}
}
}
/**
* Creates non-application specific plugins that are shared between the main
* app and the dependencies. This is used by the `optimize` command to
* pre-bundle dependencies.
*/
export async function createBaseRollupPlugins(
root: string,
resolver: InternalResolver,
options: BuildConfig
): Promise<Plugin[]> {
const {
transforms = [],
vueCustomBlockTransforms = {},
enableEsbuild = true,
enableRollupPluginVue = true
} = options
const { nodeResolve } = require('@rollup/plugin-node-resolve')
const dynamicImport = require('rollup-plugin-dynamic-import-variables')
return [
// vite:resolve
createBuildResolvePlugin(root, resolver),
// vite:esbuild
enableEsbuild ? await createEsbuildPlugin(options.jsx) : null,
// vue
enableRollupPluginVue ? await createVuePlugin(root, options) : null,
require('@rollup/plugin-json')({
preferConst: true,
indent: ' ',
compact: false,
namedExports: true
}),
// user transforms
...(transforms.length || Object.keys(vueCustomBlockTransforms).length
? [createBuildJsTransformPlugin(transforms, vueCustomBlockTransforms)]
: []),
nodeResolve({
rootDir: root,
extensions: supportedExts,
preferBuiltins: false,
dedupe: options.rollupDedupe || [],
mainFields
}),
require('@rollup/plugin-commonjs')({
extensions: ['.js', '.cjs']
}),
dynamicImport({
warnOnError: true,
include: [/\.js$/],
exclude: [/node_modules/]
})
].filter(Boolean)
}
async function createVuePlugin(
root: string,
{
vueCustomBlockTransforms = {},
rollupPluginVueOptions,
cssPreprocessOptions,
cssModuleOptions,
vueCompilerOptions,
vueTransformAssetUrls = {},
vueTemplatePreprocessOptions = {}
}: BuildConfig
) {
const {
options: postcssOptions,
plugins: postcssPlugins
} = await resolvePostcssOptions(root, true)
if (typeof vueTransformAssetUrls === 'object') {
vueTransformAssetUrls = {
includeAbsolute: true,
...vueTransformAssetUrls
}
}
return require('rollup-plugin-vue')({
...rollupPluginVueOptions,
templatePreprocessOptions: {
...vueTemplatePreprocessOptions,
pug: {
doctype: 'html',
...(vueTemplatePreprocessOptions && vueTemplatePreprocessOptions.pug)
}
},
transformAssetUrls: vueTransformAssetUrls,
postcssOptions,
postcssPlugins,
preprocessStyles: true,
preprocessOptions: cssPreprocessOptions,
preprocessCustomRequire: (id: string) => require(resolveFrom(root, id)),
compilerOptions: vueCompilerOptions,
cssModulesOptions: {
localsConvention: 'camelCase',
generateScopedName: (local: string, filename: string) =>
`${local}_${hash_sum(filename)}`,
...cssModuleOptions,
...(rollupPluginVueOptions && rollupPluginVueOptions.cssModulesOptions)
},
customBlocks: Object.keys(vueCustomBlockTransforms)
})
}
/**
* Bundles the app for production.
* Returns a Promise containing the build result.
*/
export async function build(options: BuildConfig): Promise<BuildResult> {
const {
root = process.cwd(),
base = '/',
outDir = path.resolve(root, 'dist'),
assetsDir = '_assets',
assetsInlineLimit = 4096,
assetsInclude,
cssCodeSplit = true,
alias = {},
resolvers = [],
rollupInputOptions = {},
rollupOutputOptions = {},
emitIndex = true,
emitAssets = true,
write = true,
minify = true,
terserOptions = {},
esbuildTarget = 'es2020',
enableEsbuild = true,
silent = false,
sourcemap = false,
shouldPreload = null,
env = {},
mode: configMode = 'production',
define: userDefineReplacements = {},
cssPreprocessOptions,
cssModuleOptions = {}
} = options
const isTest = process.env.NODE_ENV === 'test'
const resolvedMode = process.env.VITE_ENV || configMode
const start = Date.now()
let spinner: Ora | undefined
const msg = `Building ${configMode} bundle...`
if (!silent) {
if (process.env.DEBUG || isTest) {
console.log(msg)
} else {
spinner = require('ora')(msg + '\n').start()
}
}
await fs.emptyDir(outDir)
const indexPath = path.resolve(root, 'index.html')
const publicBasePath = base.replace(/([^/])$/, '$1/') // ensure ending slash
const resolvedAssetsPath = path.join(outDir, assetsDir)
const resolver = createResolver(root, resolvers, alias, assetsInclude)
const { htmlPlugin, renderIndex } = await createBuildHtmlPlugin(
root,
indexPath,
publicBasePath,
assetsDir,
assetsInlineLimit,
resolver,
shouldPreload
)
const basePlugins = await createBaseRollupPlugins(root, resolver, options)
// https://github.com/darionco/rollup-plugin-web-worker-loader
// configured to support `import Worker from './my-worker?worker'`
// this plugin relies on resolveId and must be placed before node-resolve
// since the latter somehow swallows ids with query strings since 8.x
basePlugins.splice(
basePlugins.findIndex((p) => p.name.includes('node-resolve')),
0,
require('rollup-plugin-web-worker-loader')({
targetPlatform: 'browser',
pattern: /(.+)\?worker$/,
extensions: supportedExts,
sourcemap: false // it's inlined so it bloats the bundle
})
)
// user env variables loaded from .env files.
// only those prefixed with VITE_ are exposed.
const userClientEnv: Record<string, string | boolean> = {}
const userEnvReplacements: Record<string, string> = {}
Object.keys(env).forEach((key) => {
if (key.startsWith(`VITE_`)) {
userEnvReplacements[`import.meta.env.${key}`] = JSON.stringify(env[key])
userClientEnv[key] = env[key]
}
})
const builtInClientEnv = {
BASE_URL: publicBasePath,
MODE: configMode,
DEV: resolvedMode !== 'production',
PROD: resolvedMode === 'production'
}
const builtInEnvReplacements: Record<string, string> = {}
Object.keys(builtInClientEnv).forEach((key) => {
builtInEnvReplacements[`import.meta.env.${key}`] = JSON.stringify(
builtInClientEnv[key as keyof typeof builtInClientEnv]
)
})
Object.keys(userDefineReplacements).forEach((key) => {
userDefineReplacements[key] = JSON.stringify(userDefineReplacements[key])
})
// lazy require rollup so that we don't load it when only using the dev server
// importing it just for the types
const rollup = require('rollup').rollup as typeof Rollup
const bundle = await rollup({
input: path.resolve(root, 'index.html'),
preserveEntrySignatures: false,
treeshake: { moduleSideEffects: 'no-external' },
onwarn: onRollupWarning(spinner, options.optimizeDeps),
...rollupInputOptions,
plugins: [
...basePlugins,
// vite:html
htmlPlugin,
// we use a custom replacement plugin because @rollup/plugin-replace
// performs replacements twice, once at transform and once at renderChunk
// - which makes it impossible to exclude Vue templates from it since
// Vue templates are compiled into js and included in chunks.
createReplacePlugin(
(id) =>
!/\?vue&type=template/.test(id) &&
// also exclude css and static assets for performance
!isCSSRequest(id) &&
!resolver.isAssetRequest(id),
{
...defaultDefines,
...userDefineReplacements,
...userEnvReplacements,
...builtInEnvReplacements,
'import.meta.env.': `({}).`,
'import.meta.env': JSON.stringify({
...userClientEnv,
...builtInClientEnv
}),
'process.env.NODE_ENV': JSON.stringify(resolvedMode),
'process.env.': `({}).`,
'process.env': JSON.stringify({ NODE_ENV: resolvedMode }),
'import.meta.hot': `false`
},
sourcemap
),
// vite:css
createBuildCssPlugin({
root,
publicBase: publicBasePath,
assetsDir,
minify,
inlineLimit: assetsInlineLimit,
cssCodeSplit,
preprocessOptions: cssPreprocessOptions,
modulesOptions: cssModuleOptions
}),
// vite:asset
createBuildAssetPlugin(
root,
resolver,
publicBasePath,
assetsDir,
assetsInlineLimit
),
createBuildWasmPlugin(root, publicBasePath, assetsDir, assetsInlineLimit),
enableEsbuild
? createEsbuildRenderChunkPlugin(esbuildTarget, minify === 'esbuild')
: undefined,
// minify with terser
// this is the default which has better compression, but slow
// the user can opt-in to use esbuild which is much faster but results
// in ~8-10% larger file size.
minify && minify !== 'esbuild'
? require('rollup-plugin-terser').terser(terserOptions)
: undefined,
// #728 user plugins should apply after `@rollup/plugin-commonjs`
// #471#issuecomment-683318951 user plugin after internal plugin
...(rollupInputOptions.plugins || [])
].filter(Boolean)
})
const { output } = await bundle.generate({
dir: resolvedAssetsPath,
format: 'es',
sourcemap,
entryFileNames: `[name].[hash].js`,
chunkFileNames: `[name].[hash].js`,
...rollupOutputOptions
})
spinner && spinner.stop()
const indexHtml = emitIndex ? renderIndex(output) : ''
if (write) {
const cwd = process.cwd()
const writeFile = async (
filepath: string,
content: string | Uint8Array,
type: WriteType
) => {
await fs.ensureDir(path.dirname(filepath))
await fs.writeFile(filepath, content)
if (!silent) {
const needCompression =
type === WriteType.JS ||
type === WriteType.CSS ||
type === WriteType.HTML
const compressed = needCompression
? `, brotli: ${(require('brotli-size').sync(content) / 1024).toFixed(
2
)}kb`
: ``
console.log(
`${chalk.gray(`[write]`)} ${writeColors[type](
path.relative(cwd, filepath)
)} ${(content.length / 1024).toFixed(2)}kb${compressed}`
)
}
}
await fs.ensureDir(outDir)
// write js chunks and assets
for (const chunk of output) {
if (chunk.type === 'chunk') {
// write chunk
const filepath = path.join(resolvedAssetsPath, chunk.fileName)
let code = chunk.code
if (chunk.map) {
code += `\n//# sourceMappingURL=${path.basename(filepath)}.map`
}
await writeFile(filepath, code, WriteType.JS)
if (chunk.map) {
await writeFile(
filepath + '.map',
chunk.map.toString(),
WriteType.SOURCE_MAP
)
}
} else if (emitAssets) {
if (!chunk.source) continue
// write asset
const filepath = path.join(resolvedAssetsPath, chunk.fileName)
await writeFile(
filepath,
chunk.source,
chunk.fileName.endsWith('.css') ? WriteType.CSS : WriteType.ASSET
)
}
}
// write html
if (indexHtml && emitIndex) {
await writeFile(
path.join(outDir, 'index.html'),
indexHtml,
WriteType.HTML
)
}
// copy over /public if it exists
if (emitAssets) {
const publicDir = path.resolve(root, 'public')
if (fs.existsSync(publicDir)) {
for (const file of await fs.readdir(publicDir)) {
await fs.copy(path.join(publicDir, file), path.resolve(outDir, file))
}
}
}
}
if (!silent) {
console.log(
`Build completed in ${((Date.now() - start) / 1000).toFixed(2)}s.\n`
)
}
// stop the esbuild service after each build
await stopService()
return {
assets: output,
html: indexHtml
}
}
/**
* Bundles the app in SSR mode.
* - All Vue dependencies are automatically externalized
* - Imports to dependencies are compiled into require() calls
* - Templates are compiled with SSR specific optimizations.
*/
export async function ssrBuild(options: BuildConfig): Promise<BuildResult> {
const {
rollupInputOptions,
rollupOutputOptions,
rollupPluginVueOptions
} = options
return build({
outDir: path.resolve(options.root || process.cwd(), 'dist-ssr'),
assetsDir: '.',
...options,
rollupPluginVueOptions: {
...rollupPluginVueOptions,
target: 'node'
},
rollupInputOptions: {
...rollupInputOptions,
external: resolveExternal(
rollupInputOptions && rollupInputOptions.external
)
},
rollupOutputOptions: {
...rollupOutputOptions,
format: 'cjs',
exports: 'named',
entryFileNames: '[name].js',
// 764 add `Symbol.toStringTag` when build es module into cjs chunk
namespaceToStringTag: true
},
emitIndex: false,
emitAssets: false,
cssCodeSplit: false,
minify: false
})
}
function resolveExternal(
userExternal: ExternalOption | undefined
): ExternalOption {
const required = ['vue', /^@vue\//]
if (!userExternal) {
return required
}
if (Array.isArray(userExternal)) {
return [...required, ...userExternal]
} else if (typeof userExternal === 'function') {
return (src, importer, isResolved) => {
if (src === 'vue' || /^@vue\//.test(src)) {
return true
}
return userExternal(src, importer, isResolved)
}
} else {
return [...required, userExternal]
}
}