vite 2.6.0-beta.0 → 2.6.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of vite might be problematic. Click here for more details.

Files changed (110) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/LICENSE.md +161 -3011
  3. package/bin/vite.js +2 -1
  4. package/dist/node/chunks/{dep-91aa74e8.js → dep-1e0a75a8.js} +58 -32
  5. package/dist/node/chunks/dep-1e0a75a8.js.map +1 -0
  6. package/dist/node/chunks/{dep-e36486f6.js → dep-ac1b4bf9.js} +1 -1
  7. package/dist/node/chunks/dep-ac1b4bf9.js.map +1 -0
  8. package/dist/node/chunks/{dep-c7e510f9.js → dep-ba6b30a0.js} +27538 -4953
  9. package/dist/node/chunks/dep-ba6b30a0.js.map +1 -0
  10. package/dist/node/chunks/{dep-11213a75.js → dep-c4cf6e92.js} +19 -6
  11. package/dist/node/chunks/dep-c4cf6e92.js.map +1 -0
  12. package/dist/node/chunks/{dep-eb6ef720.js → dep-d574094c.js} +18 -5
  13. package/dist/node/chunks/dep-d574094c.js.map +1 -0
  14. package/dist/node/chunks/{dep-0d2f9464.js → dep-e39b05d6.js} +18 -5
  15. package/dist/node/chunks/dep-e39b05d6.js.map +1 -0
  16. package/dist/node/cli.js +60 -23992
  17. package/dist/node/cli.js.map +1 -1
  18. package/dist/node/index.d.ts +26 -8
  19. package/dist/node/index.js +18 -15
  20. package/dist/node/index.js.map +1 -1
  21. package/dist/node/terser.js +102 -55
  22. package/package.json +28 -13
  23. package/types/package.json +3 -0
  24. package/api-extractor.json +0 -54
  25. package/dist/node/chunks/dep-0d2f9464.js.map +0 -1
  26. package/dist/node/chunks/dep-11213a75.js.map +0 -1
  27. package/dist/node/chunks/dep-91aa74e8.js.map +0 -1
  28. package/dist/node/chunks/dep-c7e510f9.js.map +0 -1
  29. package/dist/node/chunks/dep-e36486f6.js.map +0 -1
  30. package/dist/node/chunks/dep-eb6ef720.js.map +0 -1
  31. package/dist/node/terser.js.map +0 -1
  32. package/rollup.config.js +0 -389
  33. package/scripts/patchTypes.js +0 -70
  34. package/src/node/__tests__/asset.spec.ts +0 -156
  35. package/src/node/__tests__/build.spec.ts +0 -67
  36. package/src/node/__tests__/config.spec.ts +0 -166
  37. package/src/node/__tests__/packages/name/package.json +0 -3
  38. package/src/node/__tests__/packages/noname/package.json +0 -1
  39. package/src/node/__tests__/plugins/css.spec.ts +0 -116
  40. package/src/node/__tests__/scan.spec.ts +0 -118
  41. package/src/node/__tests__/utils.spec.ts +0 -40
  42. package/src/node/build.ts +0 -783
  43. package/src/node/cli.ts +0 -239
  44. package/src/node/config.ts +0 -1033
  45. package/src/node/constants.ts +0 -87
  46. package/src/node/importGlob.ts +0 -173
  47. package/src/node/index.ts +0 -88
  48. package/src/node/logger.ts +0 -167
  49. package/src/node/optimizer/esbuildDepPlugin.ts +0 -216
  50. package/src/node/optimizer/index.ts +0 -410
  51. package/src/node/optimizer/registerMissing.ts +0 -102
  52. package/src/node/optimizer/scan.ts +0 -457
  53. package/src/node/plugin.ts +0 -138
  54. package/src/node/plugins/asset.ts +0 -365
  55. package/src/node/plugins/assetImportMetaUrl.ts +0 -99
  56. package/src/node/plugins/clientInjections.ts +0 -72
  57. package/src/node/plugins/css.ts +0 -1279
  58. package/src/node/plugins/dataUri.ts +0 -64
  59. package/src/node/plugins/define.ts +0 -107
  60. package/src/node/plugins/esbuild.ts +0 -280
  61. package/src/node/plugins/html.ts +0 -673
  62. package/src/node/plugins/importAnalysis.ts +0 -614
  63. package/src/node/plugins/importAnalysisBuild.ts +0 -334
  64. package/src/node/plugins/index.ts +0 -69
  65. package/src/node/plugins/json.ts +0 -75
  66. package/src/node/plugins/loadFallback.ts +0 -19
  67. package/src/node/plugins/manifest.ts +0 -123
  68. package/src/node/plugins/modulePreloadPolyfill.ts +0 -100
  69. package/src/node/plugins/preAlias.ts +0 -22
  70. package/src/node/plugins/reporter.ts +0 -244
  71. package/src/node/plugins/resolve.ts +0 -925
  72. package/src/node/plugins/terser.ts +0 -40
  73. package/src/node/plugins/wasm.ts +0 -72
  74. package/src/node/plugins/worker.ts +0 -117
  75. package/src/node/preview.ts +0 -82
  76. package/src/node/server/__tests__/fixtures/none/nested/package.json +0 -3
  77. package/src/node/server/__tests__/fixtures/pnpm/nested/package.json +0 -3
  78. package/src/node/server/__tests__/fixtures/pnpm/package.json +0 -3
  79. package/src/node/server/__tests__/fixtures/pnpm/pnpm-workspace.yaml +0 -0
  80. package/src/node/server/__tests__/fixtures/yarn/nested/package.json +0 -3
  81. package/src/node/server/__tests__/fixtures/yarn/package.json +0 -6
  82. package/src/node/server/__tests__/search-root.spec.ts +0 -31
  83. package/src/node/server/hmr.ts +0 -489
  84. package/src/node/server/http.ts +0 -198
  85. package/src/node/server/index.ts +0 -705
  86. package/src/node/server/middlewares/base.ts +0 -52
  87. package/src/node/server/middlewares/error.ts +0 -98
  88. package/src/node/server/middlewares/indexHtml.ts +0 -170
  89. package/src/node/server/middlewares/proxy.ts +0 -124
  90. package/src/node/server/middlewares/spaFallback.ts +0 -32
  91. package/src/node/server/middlewares/static.ts +0 -153
  92. package/src/node/server/middlewares/time.ts +0 -18
  93. package/src/node/server/middlewares/transform.ts +0 -196
  94. package/src/node/server/moduleGraph.ts +0 -200
  95. package/src/node/server/openBrowser.ts +0 -101
  96. package/src/node/server/pluginContainer.ts +0 -546
  97. package/src/node/server/searchRoot.ts +0 -70
  98. package/src/node/server/send.ts +0 -54
  99. package/src/node/server/sourcemap.ts +0 -54
  100. package/src/node/server/transformRequest.ts +0 -168
  101. package/src/node/server/ws.ts +0 -131
  102. package/src/node/ssr/__tests__/ssrTransform.spec.ts +0 -309
  103. package/src/node/ssr/ssrExternal.ts +0 -161
  104. package/src/node/ssr/ssrManifestPlugin.ts +0 -53
  105. package/src/node/ssr/ssrModuleLoader.ts +0 -214
  106. package/src/node/ssr/ssrStacktrace.ts +0 -75
  107. package/src/node/ssr/ssrTransform.ts +0 -452
  108. package/src/node/tsconfig.json +0 -14
  109. package/src/node/utils.ts +0 -565
  110. package/tsconfig.base.json +0 -11
package/src/node/build.ts DELETED
@@ -1,783 +0,0 @@
1
- import fs from 'fs'
2
- import path from 'path'
3
- import chalk from 'chalk'
4
- import { resolveConfig, InlineConfig, ResolvedConfig } from './config'
5
- import Rollup, {
6
- Plugin,
7
- RollupBuild,
8
- RollupOptions,
9
- RollupWarning,
10
- WarningHandler,
11
- OutputOptions,
12
- RollupOutput,
13
- ExternalOption,
14
- GetManualChunk,
15
- GetModuleInfo,
16
- WatcherOptions,
17
- RollupWatcher,
18
- RollupError,
19
- ModuleFormat
20
- } from 'rollup'
21
- import { buildReporterPlugin } from './plugins/reporter'
22
- import { buildHtmlPlugin } from './plugins/html'
23
- import { buildEsbuildPlugin } from './plugins/esbuild'
24
- import { terserPlugin } from './plugins/terser'
25
- import { Terser } from 'types/terser'
26
- import { copyDir, emptyDir, lookupFile, normalizePath } from './utils'
27
- import { manifestPlugin } from './plugins/manifest'
28
- import commonjsPlugin from '@rollup/plugin-commonjs'
29
- import { RollupCommonJSOptions } from 'types/commonjs'
30
- import dynamicImportVars from '@rollup/plugin-dynamic-import-vars'
31
- import { RollupDynamicImportVarsOptions } from 'types/dynamicImportVars'
32
- import { Logger } from './logger'
33
- import { TransformOptions } from 'esbuild'
34
- import { dataURIPlugin } from './plugins/dataUri'
35
- import { buildImportAnalysisPlugin } from './plugins/importAnalysisBuild'
36
- import { resolveSSRExternal, shouldExternalizeForSSR } from './ssr/ssrExternal'
37
- import { ssrManifestPlugin } from './ssr/ssrManifestPlugin'
38
- import { isCSSRequest } from './plugins/css'
39
- import { DepOptimizationMetadata } from './optimizer'
40
- import { scanImports } from './optimizer/scan'
41
- import { assetImportMetaUrlPlugin } from './plugins/assetImportMetaUrl'
42
- import { loadFallbackPlugin } from './plugins/loadFallback'
43
-
44
- export interface BuildOptions {
45
- /**
46
- * Base public path when served in production.
47
- * @deprecated `base` is now a root-level config option.
48
- */
49
- base?: string
50
- /**
51
- * Compatibility transform target. The transform is performed with esbuild
52
- * and the lowest supported target is es2015/es6. Note this only handles
53
- * syntax transformation and does not cover polyfills (except for dynamic
54
- * import)
55
- *
56
- * Default: 'modules' - Similar to `@babel/preset-env`'s targets.esmodules,
57
- * transpile targeting browsers that natively support dynamic es module imports.
58
- * https://caniuse.com/es6-module-dynamic-import
59
- *
60
- * Another special value is 'esnext' - which only performs minimal transpiling
61
- * (for minification compat) and assumes native dynamic imports support.
62
- *
63
- * For custom targets, see https://esbuild.github.io/api/#target and
64
- * https://esbuild.github.io/content-types/#javascript for more details.
65
- */
66
- target?: 'modules' | TransformOptions['target'] | false
67
- /**
68
- * whether to inject module preload polyfill.
69
- * Note: does not apply to library mode.
70
- * @default true
71
- */
72
- polyfillModulePreload?: boolean
73
- /**
74
- * whether to inject dynamic import polyfill.
75
- * Note: does not apply to library mode.
76
- * @default false
77
- * @deprecated use plugin-legacy for browsers that don't support dynamic import
78
- */
79
- polyfillDynamicImport?: boolean
80
- /**
81
- * Directory relative from `root` where build output will be placed. If the
82
- * directory exists, it will be removed before the build.
83
- * @default 'dist'
84
- */
85
- outDir?: string
86
- /**
87
- * Directory relative from `outDir` where the built js/css/image assets will
88
- * be placed.
89
- * @default 'assets'
90
- */
91
- assetsDir?: string
92
- /**
93
- * Static asset files smaller than this number (in bytes) will be inlined as
94
- * base64 strings. Default limit is `4096` (4kb). Set to `0` to disable.
95
- * @default 4096
96
- */
97
- assetsInlineLimit?: number
98
- /**
99
- * Whether to code-split CSS. When enabled, CSS in async chunks will be
100
- * inlined as strings in the chunk and inserted via dynamically created
101
- * style tags when the chunk is loaded.
102
- * @default true
103
- */
104
- cssCodeSplit?: boolean
105
- /**
106
- * If `true`, a separate sourcemap file will be created. If 'inline', the
107
- * sourcemap will be appended to the resulting output file as data URI.
108
- * 'hidden' works like `true` except that the corresponding sourcemap
109
- * comments in the bundled files are suppressed.
110
- * @default false
111
- */
112
- sourcemap?: boolean | 'inline' | 'hidden'
113
- /**
114
- * Set to `false` to disable minification, or specify the minifier to use.
115
- * Available options are 'terser' or 'esbuild'.
116
- * @default 'terser'
117
- */
118
- minify?: boolean | 'terser' | 'esbuild'
119
- /**
120
- * Options for terser
121
- * https://terser.org/docs/api-reference#minify-options
122
- */
123
- terserOptions?: Terser.MinifyOptions
124
- /**
125
- * @deprecated Vite now uses esbuild for CSS minification.
126
- */
127
- cleanCssOptions?: any
128
- /**
129
- * Will be merged with internal rollup options.
130
- * https://rollupjs.org/guide/en/#big-list-of-options
131
- */
132
- rollupOptions?: RollupOptions
133
- /**
134
- * Options to pass on to `@rollup/plugin-commonjs`
135
- */
136
- commonjsOptions?: RollupCommonJSOptions
137
- /**
138
- * Options to pass on to `@rollup/plugin-dynamic-import-vars`
139
- */
140
- dynamicImportVarsOptions?: RollupDynamicImportVarsOptions
141
- /**
142
- * Whether to write bundle to disk
143
- * @default true
144
- */
145
- write?: boolean
146
- /**
147
- * Empty outDir on write.
148
- * @default true when outDir is a sub directory of project root
149
- */
150
- emptyOutDir?: boolean | null
151
- /**
152
- * Whether to emit a manifest.json under assets dir to map hash-less filenames
153
- * to their hashed versions. Useful when you want to generate your own HTML
154
- * instead of using the one generated by Vite.
155
- *
156
- * Example:
157
- *
158
- * ```json
159
- * {
160
- * "main.js": {
161
- * "file": "main.68fe3fad.js",
162
- * "css": "main.e6b63442.css",
163
- * "imports": [...],
164
- * "dynamicImports": [...]
165
- * }
166
- * }
167
- * ```
168
- * @default false
169
- */
170
- manifest?: boolean
171
- /**
172
- * Build in library mode. The value should be the global name of the lib in
173
- * UMD mode. This will produce esm + cjs + umd bundle formats with default
174
- * configurations that are suitable for distributing libraries.
175
- */
176
- lib?: LibraryOptions | false
177
- /**
178
- * Produce SSR oriented build. Note this requires specifying SSR entry via
179
- * `rollupOptions.input`.
180
- */
181
- ssr?: boolean | string
182
- /**
183
- * Generate SSR manifest for determining style links and asset preload
184
- * directives in production.
185
- */
186
- ssrManifest?: boolean
187
- /**
188
- * Set to false to disable reporting compressed chunk sizes.
189
- * Can slightly improve build speed.
190
- */
191
- reportCompressedSize?: boolean
192
- /**
193
- * Set to false to disable brotli compressed size reporting for build.
194
- * Can slightly improve build speed.
195
- * @deprecated use `build.reportCompressedSize` instead.
196
- */
197
- brotliSize?: boolean
198
- /**
199
- * Adjust chunk size warning limit (in kbs).
200
- * @default 500
201
- */
202
- chunkSizeWarningLimit?: number
203
- /**
204
- * Rollup watch options
205
- * https://rollupjs.org/guide/en/#watchoptions
206
- */
207
- watch?: WatcherOptions | null
208
- }
209
-
210
- export interface LibraryOptions {
211
- entry: string
212
- name?: string
213
- formats?: LibraryFormats[]
214
- fileName?: string | ((format: ModuleFormat) => string)
215
- }
216
-
217
- export type LibraryFormats = 'es' | 'cjs' | 'umd' | 'iife'
218
-
219
- export type ResolvedBuildOptions = Required<
220
- Omit<
221
- BuildOptions,
222
- // make deprecated options optional
223
- 'base' | 'cleanCssOptions' | 'polyfillDynamicImport' | 'brotliSize'
224
- >
225
- >
226
-
227
- export function resolveBuildOptions(raw?: BuildOptions): ResolvedBuildOptions {
228
- const resolved: ResolvedBuildOptions = {
229
- target: 'modules',
230
- polyfillModulePreload: true,
231
- outDir: 'dist',
232
- assetsDir: 'assets',
233
- assetsInlineLimit: 4096,
234
- cssCodeSplit: !raw?.lib,
235
- sourcemap: false,
236
- rollupOptions: {},
237
- commonjsOptions: {
238
- include: [/node_modules/],
239
- extensions: ['.js', '.cjs'],
240
- ...raw?.commonjsOptions
241
- },
242
- dynamicImportVarsOptions: {
243
- warnOnError: true,
244
- exclude: [/node_modules/],
245
- ...raw?.dynamicImportVarsOptions
246
- },
247
- minify: raw?.ssr ? false : 'terser',
248
- terserOptions: {},
249
- write: true,
250
- emptyOutDir: null,
251
- manifest: false,
252
- lib: false,
253
- ssr: false,
254
- ssrManifest: false,
255
- reportCompressedSize: true,
256
- // brotliSize: true,
257
- chunkSizeWarningLimit: 500,
258
- watch: null,
259
- ...raw
260
- }
261
-
262
- // handle special build targets
263
- if (resolved.target === 'modules') {
264
- // Support browserslist
265
- // "defaults and supports es6-module and supports es6-module-dynamic-import",
266
- resolved.target = [
267
- 'es2019',
268
- 'edge88',
269
- 'firefox78',
270
- 'chrome87',
271
- 'safari13.1'
272
- ]
273
- } else if (resolved.target === 'esnext' && resolved.minify === 'terser') {
274
- // esnext + terser: limit to es2019 so it can be minified by terser
275
- resolved.target = 'es2019'
276
- }
277
-
278
- // normalize false string into actual false
279
- if ((resolved.minify as any) === 'false') {
280
- resolved.minify = false
281
- }
282
-
283
- return resolved
284
- }
285
-
286
- export function resolveBuildPlugins(config: ResolvedConfig): {
287
- pre: Plugin[]
288
- post: Plugin[]
289
- } {
290
- const options = config.build
291
- return {
292
- pre: [
293
- buildHtmlPlugin(config),
294
- commonjsPlugin(options.commonjsOptions),
295
- dataURIPlugin(),
296
- dynamicImportVars(options.dynamicImportVarsOptions),
297
- assetImportMetaUrlPlugin(config),
298
- ...(options.rollupOptions.plugins
299
- ? (options.rollupOptions.plugins.filter((p) => !!p) as Plugin[])
300
- : [])
301
- ],
302
- post: [
303
- buildImportAnalysisPlugin(config),
304
- buildEsbuildPlugin(config),
305
- ...(options.minify && options.minify !== 'esbuild'
306
- ? [terserPlugin(options.terserOptions)]
307
- : []),
308
- ...(options.manifest ? [manifestPlugin(config)] : []),
309
- ...(options.ssrManifest ? [ssrManifestPlugin(config)] : []),
310
- buildReporterPlugin(config),
311
- loadFallbackPlugin()
312
- ]
313
- }
314
- }
315
-
316
- /**
317
- * Track parallel build calls and only stop the esbuild service when all
318
- * builds are done. (#1098)
319
- */
320
- let parallelCallCounts = 0
321
- // we use a separate counter to track since the call may error before the
322
- // bundle is even pushed.
323
- const parallelBuilds: RollupBuild[] = []
324
-
325
- /**
326
- * Bundles the app for production.
327
- * Returns a Promise containing the build result.
328
- */
329
- export async function build(
330
- inlineConfig: InlineConfig = {}
331
- ): Promise<RollupOutput | RollupOutput[] | RollupWatcher> {
332
- parallelCallCounts++
333
- try {
334
- return await doBuild(inlineConfig)
335
- } finally {
336
- parallelCallCounts--
337
- if (parallelCallCounts <= 0) {
338
- await Promise.all(parallelBuilds.map((bundle) => bundle.close()))
339
- parallelBuilds.length = 0
340
- }
341
- }
342
- }
343
-
344
- async function doBuild(
345
- inlineConfig: InlineConfig = {}
346
- ): Promise<RollupOutput | RollupOutput[] | RollupWatcher> {
347
- const config = await resolveConfig(inlineConfig, 'build', 'production')
348
- const options = config.build
349
- const ssr = !!options.ssr
350
- const libOptions = options.lib
351
-
352
- config.logger.info(
353
- chalk.cyan(
354
- `vite v${require('vite/package.json').version} ${chalk.green(
355
- `building ${ssr ? `SSR bundle ` : ``}for ${config.mode}...`
356
- )}`
357
- )
358
- )
359
-
360
- const resolve = (p: string) => path.resolve(config.root, p)
361
- const input = libOptions
362
- ? resolve(libOptions.entry)
363
- : typeof options.ssr === 'string'
364
- ? resolve(options.ssr)
365
- : options.rollupOptions?.input || resolve('index.html')
366
-
367
- if (ssr && typeof input === 'string' && input.endsWith('.html')) {
368
- throw new Error(
369
- `rollupOptions.input should not be an html file when building for SSR. ` +
370
- `Please specify a dedicated SSR entry.`
371
- )
372
- }
373
-
374
- const outDir = resolve(options.outDir)
375
-
376
- // inject ssr arg to plugin load/transform hooks
377
- const plugins = (
378
- ssr ? config.plugins.map((p) => injectSsrFlagToHooks(p)) : config.plugins
379
- ) as Plugin[]
380
-
381
- // inject ssrExternal if present
382
- const userExternal = options.rollupOptions?.external
383
- let external = userExternal
384
- if (ssr) {
385
- // see if we have cached deps data available
386
- let knownImports: string[] | undefined
387
- if (config.cacheDir) {
388
- const dataPath = path.join(config.cacheDir, '_metadata.json')
389
- try {
390
- const data = JSON.parse(
391
- fs.readFileSync(dataPath, 'utf-8')
392
- ) as DepOptimizationMetadata
393
- knownImports = Object.keys(data.optimized)
394
- } catch (e) {}
395
- }
396
- if (!knownImports) {
397
- // no dev deps optimization data, do a fresh scan
398
- knownImports = Object.keys((await scanImports(config)).deps)
399
- }
400
- external = resolveExternal(
401
- resolveSSRExternal(config, knownImports),
402
- userExternal
403
- )
404
- }
405
-
406
- const rollup = require('rollup') as typeof Rollup
407
- const rollupOptions: RollupOptions = {
408
- input,
409
- preserveEntrySignatures: ssr
410
- ? 'allow-extension'
411
- : libOptions
412
- ? 'strict'
413
- : false,
414
- ...options.rollupOptions,
415
- plugins,
416
- external,
417
- onwarn(warning, warn) {
418
- onRollupWarning(warning, warn, config)
419
- }
420
- }
421
-
422
- const outputBuildError = (e: RollupError) => {
423
- let msg = chalk.red((e.plugin ? `[${e.plugin}] ` : '') + e.message)
424
- if (e.id) {
425
- msg += `\nfile: ${chalk.cyan(
426
- e.id + (e.loc ? `:${e.loc.line}:${e.loc.column}` : '')
427
- )}`
428
- }
429
- if (e.frame) {
430
- msg += `\n` + chalk.yellow(e.frame)
431
- }
432
- config.logger.error(msg, { error: e })
433
- }
434
-
435
- try {
436
- const buildOutputOptions = (output: OutputOptions = {}): OutputOptions => {
437
- return {
438
- dir: outDir,
439
- format: ssr ? 'cjs' : 'es',
440
- exports: ssr ? 'named' : 'auto',
441
- sourcemap: options.sourcemap,
442
- name: libOptions ? libOptions.name : undefined,
443
- entryFileNames: ssr
444
- ? `[name].js`
445
- : libOptions
446
- ? resolveLibFilename(libOptions, output.format || 'es', config.root)
447
- : path.posix.join(options.assetsDir, `[name].[hash].js`),
448
- chunkFileNames: libOptions
449
- ? `[name].js`
450
- : path.posix.join(options.assetsDir, `[name].[hash].js`),
451
- assetFileNames: libOptions
452
- ? `[name].[ext]`
453
- : path.posix.join(options.assetsDir, `[name].[hash].[ext]`),
454
- // #764 add `Symbol.toStringTag` when build es module into cjs chunk
455
- // #1048 add `Symbol.toStringTag` for module default export
456
- namespaceToStringTag: true,
457
- inlineDynamicImports: ssr && typeof input === 'string',
458
- manualChunks:
459
- !ssr &&
460
- !libOptions &&
461
- output?.format !== 'umd' &&
462
- output?.format !== 'iife'
463
- ? createMoveToVendorChunkFn(config)
464
- : undefined,
465
- ...output
466
- }
467
- }
468
-
469
- // resolve lib mode outputs
470
- const outputs = resolveBuildOutputs(
471
- options.rollupOptions?.output,
472
- libOptions,
473
- config.logger
474
- )
475
-
476
- // watch file changes with rollup
477
- if (config.build.watch) {
478
- config.logger.info(chalk.cyanBright(`\nwatching for file changes...`))
479
-
480
- const output: OutputOptions[] = []
481
- if (Array.isArray(outputs)) {
482
- for (const resolvedOutput of outputs) {
483
- output.push(buildOutputOptions(resolvedOutput))
484
- }
485
- } else {
486
- output.push(buildOutputOptions(outputs))
487
- }
488
-
489
- const watcherOptions = config.build.watch
490
- const watcher = rollup.watch({
491
- ...rollupOptions,
492
- output,
493
- watch: {
494
- ...watcherOptions,
495
- chokidar: {
496
- ignored: [
497
- '**/node_modules/**',
498
- '**/.git/**',
499
- ...(watcherOptions?.chokidar?.ignored || [])
500
- ],
501
- ignoreInitial: true,
502
- ignorePermissionErrors: true,
503
- ...watcherOptions.chokidar
504
- }
505
- }
506
- })
507
-
508
- watcher.on('event', (event) => {
509
- if (event.code === 'BUNDLE_START') {
510
- config.logger.info(chalk.cyanBright(`\nbuild started...`))
511
- if (options.write) {
512
- prepareOutDir(outDir, options.emptyOutDir, config)
513
- }
514
- } else if (event.code === 'BUNDLE_END') {
515
- event.result.close()
516
- config.logger.info(chalk.cyanBright(`built in ${event.duration}ms.`))
517
- } else if (event.code === 'ERROR') {
518
- outputBuildError(event.error)
519
- }
520
- })
521
-
522
- // stop watching
523
- watcher.close()
524
-
525
- return watcher
526
- }
527
-
528
- // write or generate files with rollup
529
- const bundle = await rollup.rollup(rollupOptions)
530
- parallelBuilds.push(bundle)
531
-
532
- const generate = (output: OutputOptions = {}) => {
533
- return bundle[options.write ? 'write' : 'generate'](
534
- buildOutputOptions(output)
535
- )
536
- }
537
-
538
- if (options.write) {
539
- prepareOutDir(outDir, options.emptyOutDir, config)
540
- }
541
-
542
- if (Array.isArray(outputs)) {
543
- const res = []
544
- for (const output of outputs) {
545
- res.push(await generate(output))
546
- }
547
- return res
548
- } else {
549
- return await generate(outputs)
550
- }
551
- } catch (e) {
552
- outputBuildError(e)
553
- throw e
554
- }
555
- }
556
-
557
- function prepareOutDir(
558
- outDir: string,
559
- emptyOutDir: boolean | null,
560
- config: ResolvedConfig
561
- ) {
562
- if (fs.existsSync(outDir)) {
563
- if (
564
- emptyOutDir == null &&
565
- !normalizePath(outDir).startsWith(config.root + '/')
566
- ) {
567
- // warn if outDir is outside of root
568
- config.logger.warn(
569
- chalk.yellow(
570
- `\n${chalk.bold(`(!)`)} outDir ${chalk.white.dim(
571
- outDir
572
- )} is not inside project root and will not be emptied.\n` +
573
- `Use --emptyOutDir to override.\n`
574
- )
575
- )
576
- } else if (emptyOutDir !== false) {
577
- emptyDir(outDir, ['.git'])
578
- }
579
- }
580
- if (config.publicDir && fs.existsSync(config.publicDir)) {
581
- copyDir(config.publicDir, outDir)
582
- }
583
- }
584
-
585
- function getPkgName(root: string) {
586
- const { name } = JSON.parse(lookupFile(root, ['package.json']) || `{}`)
587
-
588
- return name?.startsWith('@') ? name.split('/')[1] : name
589
- }
590
-
591
- function createMoveToVendorChunkFn(config: ResolvedConfig): GetManualChunk {
592
- const cache = new Map<string, boolean>()
593
- return (id, { getModuleInfo }) => {
594
- if (
595
- id.includes('node_modules') &&
596
- !isCSSRequest(id) &&
597
- staticImportedByEntry(id, getModuleInfo, cache)
598
- ) {
599
- return 'vendor'
600
- }
601
- }
602
- }
603
-
604
- function staticImportedByEntry(
605
- id: string,
606
- getModuleInfo: GetModuleInfo,
607
- cache: Map<string, boolean>,
608
- importStack: string[] = []
609
- ): boolean {
610
- if (cache.has(id)) {
611
- return cache.get(id) as boolean
612
- }
613
- if (importStack.includes(id)) {
614
- // circular deps!
615
- cache.set(id, false)
616
- return false
617
- }
618
- const mod = getModuleInfo(id)
619
- if (!mod) {
620
- cache.set(id, false)
621
- return false
622
- }
623
-
624
- if (mod.isEntry) {
625
- cache.set(id, true)
626
- return true
627
- }
628
- const someImporterIs = mod.importers.some((importer) =>
629
- staticImportedByEntry(
630
- importer,
631
- getModuleInfo,
632
- cache,
633
- importStack.concat(id)
634
- )
635
- )
636
- cache.set(id, someImporterIs)
637
- return someImporterIs
638
- }
639
-
640
- export function resolveLibFilename(
641
- libOptions: LibraryOptions,
642
- format: ModuleFormat,
643
- root: string
644
- ): string {
645
- if (typeof libOptions.fileName === 'function') {
646
- return libOptions.fileName(format)
647
- }
648
-
649
- const name = libOptions.fileName || getPkgName(root)
650
-
651
- if (!name)
652
- throw new Error(
653
- 'Name in package.json is required if option "build.lib.fileName" is not provided.'
654
- )
655
-
656
- return `${name}.${format}.js`
657
- }
658
-
659
- function resolveBuildOutputs(
660
- outputs: OutputOptions | OutputOptions[] | undefined,
661
- libOptions: LibraryOptions | false,
662
- logger: Logger
663
- ): OutputOptions | OutputOptions[] | undefined {
664
- if (libOptions) {
665
- const formats = libOptions.formats || ['es', 'umd']
666
- if (
667
- (formats.includes('umd') || formats.includes('iife')) &&
668
- !libOptions.name
669
- ) {
670
- throw new Error(
671
- `Option "build.lib.name" is required when output formats ` +
672
- `include "umd" or "iife".`
673
- )
674
- }
675
- if (!outputs) {
676
- return formats.map((format) => ({ format }))
677
- } else if (!Array.isArray(outputs)) {
678
- return formats.map((format) => ({ ...outputs, format }))
679
- } else if (libOptions.formats) {
680
- // user explicitly specifying own output array
681
- logger.warn(
682
- chalk.yellow(
683
- `"build.lib.formats" will be ignored because ` +
684
- `"build.rollupOptions.output" is already an array format`
685
- )
686
- )
687
- }
688
- }
689
- return outputs
690
- }
691
-
692
- const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`]
693
- const dynamicImportWarningIgnoreList = [
694
- `Unsupported expression`,
695
- `statically analyzed`
696
- ]
697
-
698
- export function onRollupWarning(
699
- warning: RollupWarning,
700
- warn: WarningHandler,
701
- config: ResolvedConfig
702
- ): void {
703
- if (warning.code === 'UNRESOLVED_IMPORT') {
704
- const id = warning.source
705
- const importer = warning.importer
706
- // throw unless it's commonjs external...
707
- if (!importer || !/\?commonjs-external$/.test(importer)) {
708
- throw new Error(
709
- `[vite]: Rollup failed to resolve import "${id}" from "${importer}".\n` +
710
- `This is most likely unintended because it can break your application at runtime.\n` +
711
- `If you do want to externalize this module explicitly add it to\n` +
712
- `\`build.rollupOptions.external\``
713
- )
714
- }
715
- }
716
-
717
- if (
718
- warning.plugin === 'rollup-plugin-dynamic-import-variables' &&
719
- dynamicImportWarningIgnoreList.some((msg) => warning.message.includes(msg))
720
- ) {
721
- return
722
- }
723
-
724
- if (!warningIgnoreList.includes(warning.code!)) {
725
- const userOnWarn = config.build.rollupOptions?.onwarn
726
- if (userOnWarn) {
727
- userOnWarn(warning, warn)
728
- } else if (warning.code === 'PLUGIN_WARNING') {
729
- config.logger.warn(
730
- `${chalk.bold.yellow(`[plugin:${warning.plugin}]`)} ${chalk.yellow(
731
- warning.message
732
- )}`
733
- )
734
- } else {
735
- warn(warning)
736
- }
737
- }
738
- }
739
-
740
- function resolveExternal(
741
- ssrExternals: string[],
742
- user: ExternalOption | undefined
743
- ): ExternalOption {
744
- return ((id, parentId, isResolved) => {
745
- if (shouldExternalizeForSSR(id, ssrExternals)) {
746
- return true
747
- }
748
- if (user) {
749
- if (typeof user === 'function') {
750
- return user(id, parentId, isResolved)
751
- } else if (Array.isArray(user)) {
752
- return user.some((test) => isExternal(id, test))
753
- } else {
754
- return isExternal(id, user)
755
- }
756
- }
757
- }) as ExternalOption
758
- }
759
-
760
- function isExternal(id: string, test: string | RegExp) {
761
- if (typeof test === 'string') {
762
- return id === test
763
- } else {
764
- return test.test(id)
765
- }
766
- }
767
-
768
- function injectSsrFlagToHooks(p: Plugin): Plugin {
769
- const { resolveId, load, transform } = p
770
- return {
771
- ...p,
772
- resolveId: wrapSsrHook(resolveId),
773
- load: wrapSsrHook(load),
774
- transform: wrapSsrHook(transform)
775
- }
776
- }
777
-
778
- function wrapSsrHook(fn: Function | undefined) {
779
- if (!fn) return
780
- return function (this: any, ...args: any[]) {
781
- return fn.call(this, ...args, true)
782
- }
783
- }