-
-
Notifications
You must be signed in to change notification settings - Fork 6.4k
/
Copy pathbuild.ts
1225 lines (1127 loc) · 36.2 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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import fs from 'node:fs'
import path from 'node:path'
import colors from 'picocolors'
import type {
ExternalOption,
InputOption,
InternalModuleFormat,
LoggingFunction,
ModuleFormat,
OutputOptions,
Plugin,
RollupBuild,
RollupError,
RollupLog,
RollupOptions,
RollupOutput,
RollupWarning,
RollupWatcher,
WatcherOptions,
} from 'rollup'
import type { Terser } from 'dep-types/terser'
import commonjsPlugin from '@rollup/plugin-commonjs'
import type { RollupCommonJSOptions } from 'dep-types/commonjs'
import type { RollupDynamicImportVarsOptions } from 'dep-types/dynamicImportVars'
import type { TransformOptions } from 'esbuild'
import type { InlineConfig, ResolvedConfig } from './config'
import { isDepsOptimizerEnabled, resolveConfig } from './config'
import { buildReporterPlugin } from './plugins/reporter'
import { buildEsbuildPlugin } from './plugins/esbuild'
import { terserPlugin } from './plugins/terser'
import {
asyncFlatten,
copyDir,
emptyDir,
joinUrlSegments,
normalizePath,
requireResolveFromRootWithFallback,
} from './utils'
import { manifestPlugin } from './plugins/manifest'
import type { Logger } from './logger'
import { dataURIPlugin } from './plugins/dataUri'
import { buildImportAnalysisPlugin } from './plugins/importAnalysisBuild'
import {
cjsShouldExternalizeForSSR,
cjsSsrResolveExternals,
} from './ssr/ssrExternal'
import { ssrManifestPlugin } from './ssr/ssrManifestPlugin'
import type { DepOptimizationMetadata } from './optimizer'
import {
findKnownImports,
getDepsCacheDir,
initDepsOptimizer,
} from './optimizer'
import { loadFallbackPlugin } from './plugins/loadFallback'
import { findNearestPackageData } from './packages'
import type { PackageCache } from './packages'
import { ensureWatchPlugin } from './plugins/ensureWatch'
import { ESBUILD_MODULES_TARGET, VERSION } from './constants'
import { resolveChokidarOptions } from './watch'
import { completeSystemWrapPlugin } from './plugins/completeSystemWrap'
import { mergeConfig } from './publicUtils'
import { webWorkerPostPlugin } from './plugins/worker'
export interface BuildOptions {
/**
* 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 dynamic es module imports.
* https://caniuse.com/es6-module-dynamic-import
*
* Another special value is 'esnext' - which only performs minimal transpiling
* (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.
* @default 'modules'
*/
target?: 'modules' | TransformOptions['target'] | false
/**
* whether to inject module preload polyfill.
* Note: does not apply to library mode.
* @default true
* @deprecated use `modulePreload.polyfill` instead
*/
polyfillModulePreload?: boolean
/**
* Configure module preload
* Note: does not apply to library mode.
* @default true
*/
modulePreload?: boolean | ModulePreloadOptions
/**
* 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
/**
* An optional separate target for CSS minification.
* As esbuild only supports configuring targets to mainstream
* browsers, users may need this option when they are targeting
* a niche browser that comes with most modern JavaScript features
* but has poor CSS support, e.g. Android WeChat WebView, which
* doesn't support the #RGBA syntax.
* @default target
*/
cssTarget?: TransformOptions['target'] | false
/**
* Override CSS minification specifically instead of defaulting to `build.minify`,
* so you can configure minification for JS and CSS separately.
* @default 'esbuild'
*/
cssMinify?: boolean | 'esbuild' | 'lightningcss'
/**
* If `true`, a separate sourcemap file will be created. If 'inline', the
* sourcemap will be appended to the resulting output file as data URI.
* 'hidden' works like `true` except that the corresponding sourcemap
* comments in the bundled files are suppressed.
* @default false
*/
sourcemap?: boolean | 'inline' | 'hidden'
/**
* Set to `false` to disable minification, or specify the minifier to use.
* Available options are 'terser' or 'esbuild'.
* @default 'esbuild'
*/
minify?: boolean | 'terser' | 'esbuild'
/**
* Options for terser
* https://terser.org/docs/api-reference#minify-options
*/
terserOptions?: Terser.MinifyOptions
/**
* Will be merged with internal rollup options.
* https://rollupjs.org/configuration-options/
*/
rollupOptions?: RollupOptions
/**
* Options to pass on to `@rollup/plugin-commonjs`
*/
commonjsOptions?: RollupCommonJSOptions
/**
* Options to pass on to `@rollup/plugin-dynamic-import-vars`
*/
dynamicImportVarsOptions?: RollupDynamicImportVarsOptions
/**
* 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
/**
* Copy the public directory to outDir on write.
* @default true
* @experimental
*/
copyPublicDir?: boolean
/**
* 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",
* "css": "main.e6b63442.css",
* "imports": [...],
* "dynamicImports": [...]
* }
* }
* ```
* @default false
*/
manifest?: boolean | string
/**
* 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.
* @default false
*/
lib?: LibraryOptions | false
/**
* Produce SSR oriented build. Note this requires specifying SSR entry via
* `rollupOptions.input`.
* @default false
*/
ssr?: boolean | string
/**
* Generate SSR manifest for determining style links and asset preload
* directives in production.
* @default false
*/
ssrManifest?: boolean | string
/**
* Emit assets during SSR.
* @experimental
* @default false
*/
ssrEmitAssets?: boolean
/**
* Set to false to disable reporting compressed chunk sizes.
* Can slightly improve build speed.
* @default true
*/
reportCompressedSize?: boolean
/**
* Adjust chunk size warning limit (in kbs).
* @default 500
*/
chunkSizeWarningLimit?: number
/**
* Rollup watch options
* https://rollupjs.org/configuration-options/#watch
* @default null
*/
watch?: WatcherOptions | null
}
export interface LibraryOptions {
/**
* Path of library entry
*/
entry: InputOption
/**
* The name of the exposed global variable. Required when the `formats` option includes
* `umd` or `iife`
*/
name?: string
/**
* Output bundle formats
* @default ['es', 'umd']
*/
formats?: LibraryFormats[]
/**
* The name of the package file output. The default file name is the name option
* of the project package.json. It can also be defined as a function taking the
* format as an argument.
*/
fileName?: string | ((format: ModuleFormat, entryName: string) => string)
}
export type LibraryFormats = 'es' | 'cjs' | 'umd' | 'iife'
export interface ModulePreloadOptions {
/**
* Whether to inject a module preload polyfill.
* Note: does not apply to library mode.
* @default true
*/
polyfill?: boolean
/**
* Resolve the list of dependencies to preload for a given dynamic import
* @experimental
*/
resolveDependencies?: ResolveModulePreloadDependenciesFn
}
export interface ResolvedModulePreloadOptions {
polyfill: boolean
resolveDependencies?: ResolveModulePreloadDependenciesFn
}
export type ResolveModulePreloadDependenciesFn = (
filename: string,
deps: string[],
context: {
hostId: string
hostType: 'html' | 'js'
},
) => string[]
export interface ResolvedBuildOptions
extends Required<Omit<BuildOptions, 'polyfillModulePreload'>> {
modulePreload: false | ResolvedModulePreloadOptions
}
export function resolveBuildOptions(
raw: BuildOptions | undefined,
logger: Logger,
root: string,
): ResolvedBuildOptions {
const deprecatedPolyfillModulePreload = raw?.polyfillModulePreload
if (raw) {
const { polyfillModulePreload, ...rest } = raw
raw = rest
if (deprecatedPolyfillModulePreload !== undefined) {
logger.warn(
'polyfillModulePreload is deprecated. Use modulePreload.polyfill instead.',
)
}
if (
deprecatedPolyfillModulePreload === false &&
raw.modulePreload === undefined
) {
raw.modulePreload = { polyfill: false }
}
}
const modulePreload = raw?.modulePreload
const defaultModulePreload = {
polyfill: true,
}
const defaultBuildOptions: BuildOptions = {
outDir: 'dist',
assetsDir: 'assets',
assetsInlineLimit: 4096,
cssCodeSplit: !raw?.lib,
sourcemap: false,
rollupOptions: {},
minify: raw?.ssr ? false : 'esbuild',
terserOptions: {},
write: true,
emptyOutDir: null,
copyPublicDir: true,
manifest: false,
lib: false,
ssr: false,
ssrManifest: false,
ssrEmitAssets: false,
reportCompressedSize: true,
chunkSizeWarningLimit: 500,
watch: null,
}
const userBuildOptions = raw
? mergeConfig(defaultBuildOptions, raw)
: defaultBuildOptions
// @ts-expect-error Fallback options instead of merging
const resolved: ResolvedBuildOptions = {
target: 'modules',
cssTarget: false,
...userBuildOptions,
commonjsOptions: {
include: [/node_modules/],
extensions: ['.js', '.cjs'],
...userBuildOptions.commonjsOptions,
},
dynamicImportVarsOptions: {
warnOnError: true,
exclude: [/node_modules/],
...userBuildOptions.dynamicImportVarsOptions,
},
// Resolve to false | object
modulePreload:
modulePreload === false
? false
: typeof modulePreload === 'object'
? {
...defaultModulePreload,
...modulePreload,
}
: defaultModulePreload,
}
// handle special build targets
if (resolved.target === 'modules') {
resolved.target = ESBUILD_MODULES_TARGET
} else if (resolved.target === 'esnext' && resolved.minify === 'terser') {
try {
const terserPackageJsonPath = requireResolveFromRootWithFallback(
root,
'terser/package.json',
)
const terserPackageJson = JSON.parse(
fs.readFileSync(terserPackageJsonPath, 'utf-8'),
)
const v = terserPackageJson.version.split('.')
if (v[0] === '5' && v[1] < 16) {
// esnext + terser 5.16<: limit to es2021 so it can be minified by terser
resolved.target = 'es2021'
}
} catch {}
}
if (!resolved.cssTarget) {
resolved.cssTarget = resolved.target
}
// normalize false string into actual false
if ((resolved.minify as any) === 'false') {
resolved.minify = false
}
if (resolved.minify === true) {
resolved.minify = 'esbuild'
}
if (resolved.cssMinify == null) {
resolved.cssMinify = !!resolved.minify
}
return resolved
}
export async function resolveBuildPlugins(config: ResolvedConfig): Promise<{
pre: Plugin[]
post: Plugin[]
}> {
const options = config.build
const { commonjsOptions } = options
const usePluginCommonjs =
!Array.isArray(commonjsOptions?.include) ||
commonjsOptions?.include.length !== 0
const rollupOptionsPlugins = options.rollupOptions.plugins
return {
pre: [
completeSystemWrapPlugin(),
...(options.watch ? [ensureWatchPlugin()] : []),
...(usePluginCommonjs ? [commonjsPlugin(options.commonjsOptions)] : []),
dataURIPlugin(),
...((
await asyncFlatten(
Array.isArray(rollupOptionsPlugins)
? rollupOptionsPlugins
: [rollupOptionsPlugins],
)
).filter(Boolean) as Plugin[]),
...(config.isWorker ? [webWorkerPostPlugin()] : []),
],
post: [
buildImportAnalysisPlugin(config),
...(config.esbuild !== false ? [buildEsbuildPlugin(config)] : []),
...(options.minify ? [terserPlugin(config)] : []),
...(!config.isWorker
? [
...(options.manifest ? [manifestPlugin(config)] : []),
...(options.ssrManifest ? [ssrManifestPlugin(config)] : []),
buildReporterPlugin(config),
]
: []),
loadFallbackPlugin(),
],
}
}
/**
* Bundles the app for production.
* Returns a Promise containing the build result.
*/
export async function build(
inlineConfig: InlineConfig = {},
): Promise<RollupOutput | RollupOutput[] | RollupWatcher> {
const config = await resolveConfig(
inlineConfig,
'build',
'production',
'production',
)
const options = config.build
const ssr = !!options.ssr
const libOptions = options.lib
config.logger.info(
colors.cyan(
`vite v${VERSION} ${colors.green(
`building ${ssr ? `SSR bundle ` : ``}for ${config.mode}...`,
)}`,
),
)
const resolve = (p: string) => path.resolve(config.root, p)
const input = libOptions
? options.rollupOptions?.input ||
(typeof libOptions.entry === 'string'
? resolve(libOptions.entry)
: Array.isArray(libOptions.entry)
? libOptions.entry.map(resolve)
: Object.fromEntries(
Object.entries(libOptions.entry).map(([alias, file]) => [
alias,
resolve(file),
]),
))
: 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)
// inject ssr arg to plugin load/transform hooks
const plugins = (
ssr ? config.plugins.map((p) => injectSsrFlagToHooks(p)) : config.plugins
) as Plugin[]
const userExternal = options.rollupOptions?.external
let external = userExternal
// In CJS, we can pass the externals to rollup as is. In ESM, we need to
// do it in the resolve plugin so we can add the resolved extension for
// deep node_modules imports
if (ssr && config.legacy?.buildSsrCjsExternalHeuristics) {
external = await cjsSsrResolveExternal(config, userExternal)
}
if (isDepsOptimizerEnabled(config, ssr)) {
await initDepsOptimizer(config)
}
const rollupOptions: RollupOptions = {
context: 'globalThis',
preserveEntrySignatures: ssr
? 'allow-extension'
: libOptions
? 'strict'
: false,
cache: config.build.watch ? undefined : false,
...options.rollupOptions,
input,
plugins,
external,
onwarn(warning, warn) {
onRollupWarning(warning, warn, config)
},
}
const outputBuildError = (e: RollupError) => {
let msg = colors.red((e.plugin ? `[${e.plugin}] ` : '') + e.message)
if (e.id) {
msg += `\nfile: ${colors.cyan(
e.id + (e.loc ? `:${e.loc.line}:${e.loc.column}` : ''),
)}`
}
if (e.frame) {
msg += `\n` + colors.yellow(e.frame)
}
config.logger.error(msg, { error: e })
}
let bundle: RollupBuild | undefined
try {
const buildOutputOptions = (output: OutputOptions = {}): OutputOptions => {
// @ts-expect-error See https://github.com/vitejs/vite/issues/5812#issuecomment-984345618
if (output.output) {
config.logger.warn(
`You've set "rollupOptions.output.output" in your config. ` +
`This is deprecated and will override all Vite.js default output options. ` +
`Please use "rollupOptions.output" instead.`,
)
}
const ssrNodeBuild = ssr && config.ssr.target === 'node'
const ssrWorkerBuild = ssr && config.ssr.target === 'webworker'
const cjsSsrBuild = ssr && config.ssr.format === 'cjs'
const format = output.format || (cjsSsrBuild ? 'cjs' : 'es')
const jsExt =
ssrNodeBuild || libOptions
? resolveOutputJsExtension(
format,
findNearestPackageData(config.root, config.packageCache)?.data
.type,
)
: 'js'
return {
dir: outDir,
// Default format is 'es' for regular and for SSR builds
format,
exports: cjsSsrBuild ? 'named' : 'auto',
sourcemap: options.sourcemap,
name: libOptions ? libOptions.name : undefined,
// es2015 enables `generatedCode.symbols`
// - #764 add `Symbol.toStringTag` when build es module into cjs chunk
// - #1048 add `Symbol.toStringTag` for module default export
generatedCode: 'es2015',
entryFileNames: ssr
? `[name].${jsExt}`
: libOptions
? ({ name }) =>
resolveLibFilename(
libOptions,
format,
name,
config.root,
jsExt,
config.packageCache,
)
: path.posix.join(options.assetsDir, `[name]-[hash].${jsExt}`),
chunkFileNames: libOptions
? `[name]-[hash].${jsExt}`
: path.posix.join(options.assetsDir, `[name]-[hash].${jsExt}`),
assetFileNames: libOptions
? `[name].[ext]`
: path.posix.join(options.assetsDir, `[name]-[hash].[ext]`),
inlineDynamicImports:
output.format === 'umd' ||
output.format === 'iife' ||
(ssrWorkerBuild &&
(typeof input === 'string' || Object.keys(input).length === 1)),
...output,
}
}
// resolve lib mode outputs
const outputs = resolveBuildOutputs(
options.rollupOptions?.output,
libOptions,
config.logger,
)
const normalizedOutputs: OutputOptions[] = []
if (Array.isArray(outputs)) {
for (const resolvedOutput of outputs) {
normalizedOutputs.push(buildOutputOptions(resolvedOutput))
}
} else {
normalizedOutputs.push(buildOutputOptions(outputs))
}
const outDirs = normalizedOutputs.map(({ dir }) => resolve(dir!))
// watch file changes with rollup
if (config.build.watch) {
config.logger.info(colors.cyan(`\nwatching for file changes...`))
const resolvedChokidarOptions = resolveChokidarOptions(
config,
config.build.watch.chokidar,
)
const { watch } = await import('rollup')
const watcher = watch({
...rollupOptions,
output: normalizedOutputs,
watch: {
...config.build.watch,
chokidar: resolvedChokidarOptions,
},
})
watcher.on('event', (event) => {
if (event.code === 'BUNDLE_START') {
config.logger.info(colors.cyan(`\nbuild started...`))
if (options.write) {
prepareOutDir(outDirs, options.emptyOutDir, config)
}
} else if (event.code === 'BUNDLE_END') {
event.result.close()
config.logger.info(colors.cyan(`built in ${event.duration}ms.`))
} else if (event.code === 'ERROR') {
outputBuildError(event.error)
}
})
return watcher
}
// write or generate files with rollup
const { rollup } = await import('rollup')
bundle = await rollup(rollupOptions)
if (options.write) {
prepareOutDir(outDirs, options.emptyOutDir, config)
}
const res: RollupOutput[] = []
for (const output of normalizedOutputs) {
res.push(await bundle[options.write ? 'write' : 'generate'](output))
}
return Array.isArray(outputs) ? res : res[0]
} catch (e) {
outputBuildError(e)
throw e
} finally {
if (bundle) await bundle.close()
}
}
function prepareOutDir(
outDirs: string[],
emptyOutDir: boolean | null,
config: ResolvedConfig,
) {
const nonDuplicateDirs = new Set(outDirs)
let outside = false
if (emptyOutDir == null) {
for (const outDir of nonDuplicateDirs) {
if (
fs.existsSync(outDir) &&
!normalizePath(outDir).startsWith(config.root + '/')
) {
// warn if outDir is outside of root
config.logger.warn(
colors.yellow(
`\n${colors.bold(`(!)`)} outDir ${colors.white(
colors.dim(outDir),
)} is not inside project root and will not be emptied.\n` +
`Use --emptyOutDir to override.\n`,
),
)
outside = true
break
}
}
}
for (const outDir of nonDuplicateDirs) {
if (!outside && emptyOutDir !== false && fs.existsSync(outDir)) {
// skip those other outDirs which are nested in current outDir
const skipDirs = outDirs
.map((dir) => {
const relative = path.relative(outDir, dir)
if (
relative &&
!relative.startsWith('..') &&
!path.isAbsolute(relative)
) {
return relative
}
return ''
})
.filter(Boolean)
emptyDir(outDir, [...skipDirs, '.git'])
}
if (
config.build.copyPublicDir &&
config.publicDir &&
fs.existsSync(config.publicDir)
) {
copyDir(config.publicDir, outDir)
}
}
}
function getPkgName(name: string) {
return name?.[0] === '@' ? name.split('/')[1] : name
}
type JsExt = 'js' | 'cjs' | 'mjs'
function resolveOutputJsExtension(
format: ModuleFormat,
type: string = 'commonjs',
): JsExt {
if (type === 'module') {
return format === 'cjs' || format === 'umd' ? 'cjs' : 'js'
} else {
return format === 'es' ? 'mjs' : 'js'
}
}
export function resolveLibFilename(
libOptions: LibraryOptions,
format: ModuleFormat,
entryName: string,
root: string,
extension?: JsExt,
packageCache?: PackageCache,
): string {
if (typeof libOptions.fileName === 'function') {
return libOptions.fileName(format, entryName)
}
const packageJson = findNearestPackageData(root, packageCache)?.data
const name =
libOptions.fileName ||
(packageJson && typeof libOptions.entry === 'string'
? getPkgName(packageJson.name)
: entryName)
if (!name)
throw new Error(
'Name in package.json is required if option "build.lib.fileName" is not provided.',
)
extension ??= resolveOutputJsExtension(format, packageJson?.type)
if (format === 'cjs' || format === 'es') {
return `${name}.${extension}`
}
return `${name}.${format}.${extension}`
}
export function resolveBuildOutputs(
outputs: OutputOptions | OutputOptions[] | undefined,
libOptions: LibraryOptions | false,
logger: Logger,
): OutputOptions | OutputOptions[] | undefined {
if (libOptions) {
const libHasMultipleEntries =
typeof libOptions.entry !== 'string' &&
Object.values(libOptions.entry).length > 1
const libFormats =
libOptions.formats ||
(libHasMultipleEntries ? ['es', 'cjs'] : ['es', 'umd'])
if (!Array.isArray(outputs)) {
if (libFormats.includes('umd') || libFormats.includes('iife')) {
if (libHasMultipleEntries) {
throw new Error(
'Multiple entry points are not supported when output formats include "umd" or "iife".',
)
}
if (!libOptions.name) {
throw new Error(
'Option "build.lib.name" is required when output formats include "umd" or "iife".',
)
}
}
return libFormats.map((format) => ({ ...outputs, format }))
}
// By this point, we know "outputs" is an Array.
if (libOptions.formats) {
logger.warn(
colors.yellow(
'"build.lib.formats" will be ignored because "build.rollupOptions.output" is already an array format.',
),
)
}
outputs.forEach((output) => {
if (['umd', 'iife'].includes(output.format!) && !output.name) {
throw new Error(
'Entries in "build.rollupOptions.output" must specify "name" when the format is "umd" or "iife".',
)
}
})
}
return outputs
}
const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`]
const dynamicImportWarningIgnoreList = [
`Unsupported expression`,
`statically analyzed`,
]
export function onRollupWarning(
warning: RollupWarning,
warn: LoggingFunction,
config: ResolvedConfig,
): void {
const viteWarn: LoggingFunction = (warnLog) => {
let warning: string | RollupLog
if (typeof warnLog === 'function') {
warning = warnLog()
} else {
warning = warnLog
}
if (typeof warning === 'object') {
if (warning.code === 'UNRESOLVED_IMPORT') {
const id = warning.id
const exporter = warning.exporter
// throw unless it's commonjs external...
if (!id || !/\?commonjs-external$/.test(id)) {
throw new Error(
`[vite]: Rollup failed to resolve import "${exporter}" from "${id}".\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) =>
// @ts-expect-error warning is RollupLog
warning.message.includes(msg),
)
) {
return
}
if (warningIgnoreList.includes(warning.code!)) {
return
}
if (warning.code === 'PLUGIN_WARNING') {
config.logger.warn(
`${colors.bold(
colors.yellow(`[plugin:${warning.plugin}]`),
)} ${colors.yellow(warning.message)}`,
)
return
}
}
warn(warnLog)
}
const tty = process.stdout.isTTY && !process.env.CI
if (tty) {
process.stdout.clearLine(0)
process.stdout.cursorTo(0)
}
const userOnWarn = config.build.rollupOptions?.onwarn
if (userOnWarn) {
userOnWarn(warning, viteWarn)
} else {
viteWarn(warning)
}
}
async function cjsSsrResolveExternal(
config: ResolvedConfig,
user: ExternalOption | undefined,
): Promise<ExternalOption> {
// see if we have cached deps data available
let knownImports: string[] | undefined
const dataPath = path.join(getDepsCacheDir(config, false), '_metadata.json')
try {
const data = JSON.parse(
fs.readFileSync(dataPath, 'utf-8'),
) as DepOptimizationMetadata
knownImports = Object.keys(data.optimized)
} catch (e) {}
if (!knownImports) {
// no dev deps optimization data, do a fresh scan
knownImports = await findKnownImports(config, false) // needs to use non-ssr
}
const ssrExternals = cjsSsrResolveExternals(config, knownImports)
return (id, parentId, isResolved) => {
const isExternal = cjsShouldExternalizeForSSR(id, ssrExternals)
if (isExternal) {
return true
}
if (user) {
return resolveUserExternal(user, id, parentId, isResolved)
}
}
}
export function resolveUserExternal(
user: ExternalOption,
id: string,
parentId: string | undefined,
isResolved: boolean,
): boolean | null | void {
if (typeof user === 'function') {
return user(id, parentId, isResolved)
} else if (Array.isArray(user)) {
return user.some((test) => isExternal(id, test))
} else {
return isExternal(id, user)
}
}
function isExternal(id: string, test: string | RegExp) {
if (typeof test === 'string') {
return id === test
} else {
return test.test(id)
}
}
function injectSsrFlagToHooks(plugin: Plugin): Plugin {
const { resolveId, load, transform } = plugin
return {
...plugin,
resolveId: wrapSsrResolveId(resolveId),
load: wrapSsrLoad(load),
transform: wrapSsrTransform(transform),
}
}