/
index.ts
450 lines (416 loc) · 12.1 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
import path from 'path'
import fs from 'fs-extra'
import chalk from 'chalk'
import { Ora } from 'ora'
import { resolveFrom } from '../utils'
import {
rollup as Rollup,
RollupOutput,
ExternalOption,
Plugin,
InputOptions
} from 'rollup'
import { createResolver, supportedExts, InternalResolver } from '../resolver'
import { createBuildResolvePlugin } from './buildPluginResolve'
import { createBuildHtmlPlugin } from './buildPluginHtml'
import { createBuildCssPlugin } from './buildPluginCss'
import { createBuildAssetPlugin } from './buildPluginAsset'
import { createEsbuildPlugin } from './buildPluginEsbuild'
import { createReplacePlugin } from './buildPluginReplace'
import { stopService } from '../esbuildService'
import { BuildConfig } from '../config'
import { createBuildJsTransformPlugin } from '../transform'
import hash_sum from 'hash-sum'
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`]
export const onRollupWarning: (
spinner: Ora | undefined
) => InputOptions['onwarn'] = (spinner) => (warning, warn) => {
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()
}
}
}
/**
* Named exports detection logic from Snowpack
* MIT License
* https://github.com/pikapkg/snowpack/blob/master/LICENSE
*/
const PACKAGES_TO_AUTO_DETECT_EXPORTS = [
path.join('react', 'index.js'),
path.join('react-dom', 'index.js'),
'react-is',
'prop-types',
'scheduler',
'rxjs',
'exenv',
'body-scroll-lock'
]
function detectExports(root: string, id: string): string[] | undefined {
try {
const fileLoc = resolveFrom(root, id)
if (fs.existsSync(fileLoc)) {
return Object.keys(require(fileLoc)).filter((e) => e[0] !== '_')
}
} catch (err) {
// ignore
}
}
/**
* 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 { rollupInputOptions = {}, transforms = [] } = options
const knownNamedExports: Record<string, string[]> = {
...options.rollupPluginCommonJSNamedExports
}
for (const id of PACKAGES_TO_AUTO_DETECT_EXPORTS) {
knownNamedExports[id] =
knownNamedExports[id] || detectExports(root, id) || []
}
return [
// user plugins
...(rollupInputOptions.plugins || []),
// vite:resolve
createBuildResolvePlugin(root, resolver),
// vite:esbuild
await createEsbuildPlugin(options.minify === 'esbuild', options.jsx),
// vue
require('rollup-plugin-vue')({
...options.rollupPluginVueOptions,
transformAssetUrls: {
includeAbsolute: true
},
preprocessStyles: true,
preprocessCustomRequire: (id: string) => require(resolveFrom(root, id)),
compilerOptions: options.vueCompilerOptions,
cssModulesOptions: {
generateScopedName: (local: string, filename: string) =>
`${local}_${hash_sum(filename)}`,
...(options.rollupPluginVueOptions &&
options.rollupPluginVueOptions.cssModulesOptions)
}
}),
require('@rollup/plugin-json')({
preferConst: true,
indent: ' ',
compact: false,
namedExports: true
}),
// user transforms
...(transforms.length ? [createBuildJsTransformPlugin(transforms)] : []),
require('@rollup/plugin-node-resolve')({
rootDir: root,
extensions: supportedExts,
preferBuiltins: false
}),
require('@rollup/plugin-commonjs')({
extensions: ['.js', '.cjs'],
namedExports: knownNamedExports
})
].filter(Boolean)
}
/**
* Bundles the app for production.
* Returns a Promise containing the build result.
*/
export async function build(options: BuildConfig): Promise<BuildResult> {
if (options.ssr) {
return ssrBuild({
...options,
ssr: false // since ssrBuild calls build, this avoids an infinite loop.
})
}
const {
root = process.cwd(),
base = '/',
outDir = path.resolve(root, 'dist'),
assetsDir = '_assets',
assetsInlineLimit = 4096,
cssCodeSplit = true,
alias = {},
resolvers = [],
rollupInputOptions = {},
rollupOutputOptions = {},
emitIndex = true,
emitAssets = true,
write = true,
minify = true,
silent = false,
sourcemap = false,
shouldPreload = null,
env = {},
mode = 'production'
} = options
const isTest = process.env.NODE_ENV === 'test'
process.env.NODE_ENV = mode
const start = Date.now()
let spinner: Ora | undefined
const msg = 'Building for production...'
if (!silent) {
if (process.env.DEBUG || isTest) {
console.log(msg)
} else {
spinner = require('ora')(msg + '\n').start()
}
}
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)
const { htmlPlugin, renderIndex } = await createBuildHtmlPlugin(
root,
indexPath,
publicBasePath,
assetsDir,
assetsInlineLimit,
resolver,
shouldPreload
)
const basePlugins = await createBaseRollupPlugins(root, resolver, options)
env.NODE_ENV = mode!
const envReplacements = Object.keys(env).reduce((replacements, key) => {
replacements[`process.env.${key}`] = JSON.stringify(env[key])
return replacements
}, {} as Record<string, string>)
// 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),
...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) => /\.(j|t)sx?$/.test(id),
{
...envReplacements,
'process.env.BASE_URL': JSON.stringify(publicBasePath),
'process.env.': `({}).`,
'import.meta.hot': `false`
},
sourcemap
),
// for vite spcific replacements, make sure to only apply them to
// non-dependency code to avoid collision (e.g. #224 antd has __DEV__)
createReplacePlugin(
(id) =>
id.startsWith('/vite') ||
(!id.includes('node_modules') && /\.(j|t)sx?$/.test(id)),
{
__DEV__: `false`
},
sourcemap
),
// vite:css
createBuildCssPlugin(
root,
publicBasePath,
assetsDir,
minify,
assetsInlineLimit,
cssCodeSplit
),
// vite:asset
createBuildAssetPlugin(
root,
publicBasePath,
assetsDir,
assetsInlineLimit
),
// 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()
: undefined
]
})
const { output } = await bundle.generate({
format: 'es',
sourcemap,
entryFileNames: `[name].[hash].js`,
chunkFileNames: `[name].[hash].js`,
...rollupOutputOptions
})
spinner && spinner.stop()
const cssFileName = output.find(
(a) => a.type === 'asset' && a.fileName.endsWith('.css')
)!.fileName
const indexHtml = emitIndex ? renderIndex(output, cssFileName) : ''
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) {
console.log(
`${chalk.gray(`[write]`)} ${writeColors[type](
path.relative(cwd, filepath)
)} ${(content.length / 1024).toFixed(2)}kb, brotli: ${(
require('brotli-size').sync(content) / 1024
).toFixed(2)}kb`
)
}
}
await fs.remove(outDir)
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) {
// 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
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'
},
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]
}
}