-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
Copy pathbuild.ts
1612 lines (1483 loc) · 47.3 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,
RollupBuild,
RollupError,
RollupLog,
RollupOptions,
RollupOutput,
RollupWatcher,
WatcherOptions,
} from 'rollup'
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 { withTrailingSlash } from '../shared/utils'
import {
DEFAULT_ASSETS_INLINE_LIMIT,
ESBUILD_MODULES_TARGET,
ROLLUP_HOOKS,
VERSION,
} from './constants'
import type {
EnvironmentOptions,
InlineConfig,
ResolvedConfig,
ResolvedEnvironmentOptions,
} from './config'
import { resolveConfig } from './config'
import type { PartialEnvironment } from './baseEnvironment'
import { buildReporterPlugin } from './plugins/reporter'
import { buildEsbuildPlugin } from './plugins/esbuild'
import { type TerserOptions, terserPlugin } from './plugins/terser'
import {
arraify,
asyncFlatten,
copyDir,
displayTime,
emptyDir,
getPkgName,
joinUrlSegments,
mergeWithDefaults,
normalizePath,
partialEncodeURIPath,
} from './utils'
import { perEnvironmentPlugin, resolveEnvironmentPlugins } from './plugin'
import { manifestPlugin } from './plugins/manifest'
import type { Logger } from './logger'
import { dataURIPlugin } from './plugins/dataUri'
import { buildImportAnalysisPlugin } from './plugins/importAnalysisBuild'
import { ssrManifestPlugin } from './ssr/ssrManifestPlugin'
import { buildLoadFallbackPlugin } from './plugins/loadFallback'
import { findNearestPackageData } from './packages'
import type { PackageCache } from './packages'
import {
getResolvedOutDirs,
resolveChokidarOptions,
resolveEmptyOutDir,
} from './watch'
import { completeSystemWrapPlugin } from './plugins/completeSystemWrap'
import { mergeConfig } from './publicUtils'
import { webWorkerPostPlugin } from './plugins/worker'
import { getHookHandler } from './plugins'
import {
BaseEnvironment,
getDefaultResolvedEnvironmentOptions,
} from './baseEnvironment'
import type { MinimalPluginContext, Plugin, PluginContext } from './plugin'
import type { RollupPluginHooks } from './typeUtils'
export interface BuildEnvironmentOptions {
/**
* 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. If a callback is passed, a boolean can be returned to opt-in
* or opt-out of inlining. If nothing is returned the default logic applies.
*
* Default limit is `4096` (4 KiB). Set to `0` to disable.
* @default 4096
*/
assetsInlineLimit?:
| number
| ((filePath: string, content: Buffer) => boolean | undefined)
/**
* 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
*
* In addition, you can also pass a `maxWorkers: number` option to specify the
* max number of workers to spawn. Defaults to the number of CPUs minus 1.
*/
terserOptions?: TerserOptions
/**
* 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
*/
copyPublicDir?: boolean
/**
* Whether to emit a .vite/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.
* @default false
*/
ssrEmitAssets?: boolean
/**
* Emit assets during build. Frameworks can set environments.ssr.build.emitAssets
* By default, it is true for the client and false for other environments.
*/
emitAssets?: 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 kB).
* @default 500
*/
chunkSizeWarningLimit?: number
/**
* Rollup watch options
* https://rollupjs.org/configuration-options/#watch
* @default null
*/
watch?: WatcherOptions | null
/**
* create the Build Environment instance
*/
createEnvironment?: (
name: string,
config: ResolvedConfig,
) => Promise<BuildEnvironment> | BuildEnvironment
}
export type BuildOptions = BuildEnvironmentOptions
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)
/**
* The name of the CSS file output if the library imports CSS. Defaults to the
* same value as `build.lib.fileName` if it's set a string, otherwise it falls
* back to the name option of the project package.json.
*/
cssFileName?: string
}
export type LibraryFormats = 'es' | 'cjs' | 'umd' | 'iife' | 'system'
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 ResolvedBuildEnvironmentOptions
extends Required<Omit<BuildEnvironmentOptions, 'polyfillModulePreload'>> {
modulePreload: false | ResolvedModulePreloadOptions
}
export interface ResolvedBuildOptions
extends Required<Omit<BuildOptions, 'polyfillModulePreload'>> {
modulePreload: false | ResolvedModulePreloadOptions
}
export const buildEnvironmentOptionsDefaults = Object.freeze({
target: 'modules',
/** @deprecated */
polyfillModulePreload: true,
modulePreload: true,
outDir: 'dist',
assetsDir: 'assets',
assetsInlineLimit: DEFAULT_ASSETS_INLINE_LIMIT,
// cssCodeSplit
// cssTarget
// cssMinify
sourcemap: false,
// minify
terserOptions: {},
rollupOptions: {},
commonjsOptions: {
include: [/node_modules/],
extensions: ['.js', '.cjs'],
},
dynamicImportVarsOptions: {
warnOnError: true,
exclude: [/node_modules/],
},
write: true,
emptyOutDir: null,
copyPublicDir: true,
manifest: false,
lib: false,
// ssr
ssrManifest: false,
ssrEmitAssets: false,
// emitAssets
reportCompressedSize: true,
chunkSizeWarningLimit: 500,
watch: null,
// createEnvironment
})
export function resolveBuildEnvironmentOptions(
raw: BuildEnvironmentOptions,
logger: Logger,
consumer: 'client' | 'server' | undefined,
// Backward compatibility
isSsrTargetWebworkerEnvironment?: boolean,
): ResolvedBuildEnvironmentOptions {
const deprecatedPolyfillModulePreload = raw?.polyfillModulePreload
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 merged = mergeWithDefaults(
{
...buildEnvironmentOptionsDefaults,
cssCodeSplit: !raw.lib,
minify: consumer === 'server' ? false : 'esbuild',
ssr: consumer === 'server',
emitAssets: consumer === 'client',
createEnvironment: (name, config) => new BuildEnvironment(name, config),
} satisfies BuildEnvironmentOptions,
raw,
)
// handle special build targets
if (merged.target === 'modules') {
merged.target = ESBUILD_MODULES_TARGET
}
// normalize false string into actual false
if ((merged.minify as string) === 'false') {
merged.minify = false
} else if (merged.minify === true) {
merged.minify = 'esbuild'
}
const defaultModulePreload = {
polyfill: true,
}
const resolved: ResolvedBuildEnvironmentOptions = {
...merged,
cssTarget: merged.cssTarget ?? merged.target,
cssMinify:
merged.cssMinify ?? (consumer === 'server' ? 'esbuild' : !!merged.minify),
// Resolve to false | object
modulePreload:
merged.modulePreload === false
? false
: merged.modulePreload === true
? defaultModulePreload
: {
...defaultModulePreload,
...merged.modulePreload,
},
}
if (isSsrTargetWebworkerEnvironment) {
resolved.rollupOptions ??= {}
resolved.rollupOptions.output ??= {}
const output = resolved.rollupOptions.output
for (const out of arraify(output)) {
out.entryFileNames ??= `[name].js`
out.chunkFileNames ??= `[name]-[hash].js`
const input = resolved.rollupOptions.input
out.inlineDynamicImports ??=
!input || typeof input === 'string' || Object.keys(input).length === 1
}
}
return resolved
}
export async function resolveBuildPlugins(config: ResolvedConfig): Promise<{
pre: Plugin[]
post: Plugin[]
}> {
return {
pre: [
completeSystemWrapPlugin(),
perEnvironmentPlugin('commonjs', (environment) => {
const { commonjsOptions } = environment.config.build
const usePluginCommonjs =
!Array.isArray(commonjsOptions.include) ||
commonjsOptions.include.length !== 0
return usePluginCommonjs ? commonjsPlugin(commonjsOptions) : false
}),
dataURIPlugin(),
perEnvironmentPlugin(
'vite:rollup-options-plugins',
async (environment) =>
(
await asyncFlatten(
arraify(environment.config.build.rollupOptions.plugins),
)
).filter(Boolean) as Plugin[],
),
...(config.isWorker ? [webWorkerPostPlugin()] : []),
],
post: [
buildImportAnalysisPlugin(config),
...(config.esbuild !== false ? [buildEsbuildPlugin(config)] : []),
terserPlugin(config),
...(!config.isWorker
? [manifestPlugin(), ssrManifestPlugin(), buildReporterPlugin(config)]
: []),
buildLoadFallbackPlugin(),
],
}
}
/**
* Bundles a single environment for production.
* Returns a Promise containing the build result.
*/
export async function build(
inlineConfig: InlineConfig = {},
): Promise<RollupOutput | RollupOutput[] | RollupWatcher> {
const builder = await createBuilder(inlineConfig, true)
const environment = Object.values(builder.environments)[0]
if (!environment) throw new Error('No environment found')
return builder.build(environment)
}
function resolveConfigToBuild(
inlineConfig: InlineConfig = {},
patchConfig?: (config: ResolvedConfig) => void,
patchPlugins?: (resolvedPlugins: Plugin[]) => void,
): Promise<ResolvedConfig> {
return resolveConfig(
inlineConfig,
'build',
'production',
'production',
false,
patchConfig,
patchPlugins,
)
}
/**
* Build an App environment, or a App library (if libraryOptions is provided)
**/
async function buildEnvironment(
environment: BuildEnvironment,
): Promise<RollupOutput | RollupOutput[] | RollupWatcher> {
const { root, packageCache } = environment.config
const options = environment.config.build
const libOptions = options.lib
const { logger } = environment
const ssr = environment.config.consumer === 'server'
logger.info(
colors.cyan(
`vite v${VERSION} ${colors.green(
`building ${ssr ? `SSR bundle ` : ``}for ${environment.config.mode}...`,
)}`,
),
)
const resolve = (p: string) => path.resolve(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.`,
)
}
if (options.cssCodeSplit === false) {
const inputs =
typeof input === 'string'
? [input]
: Array.isArray(input)
? input
: Object.values(input)
if (inputs.some((input) => input.endsWith('.css'))) {
throw new Error(
`When "build.cssCodeSplit: false" is set, "rollupOptions.input" should not include CSS files.`,
)
}
}
const outDir = resolve(options.outDir)
// inject environment and ssr arg to plugin load/transform hooks
const plugins = environment.plugins.map((p) =>
injectEnvironmentToHooks(environment, p),
)
const rollupOptions: RollupOptions = {
preserveEntrySignatures: ssr
? 'allow-extension'
: libOptions
? 'strict'
: false,
cache: options.watch ? undefined : false,
...options.rollupOptions,
output: options.rollupOptions.output,
input,
plugins,
external: options.rollupOptions?.external,
onwarn(warning, warn) {
onRollupWarning(warning, warn, environment)
},
}
/**
* The stack string usually contains a copy of the message at the start of the stack.
* If the stack starts with the message, we remove it and just return the stack trace
* portion. Otherwise the original stack trace is used.
*/
function extractStack(e: RollupError) {
const { stack, name = 'Error', message } = e
// If we don't have a stack, not much we can do.
if (!stack) {
return stack
}
const expectedPrefix = `${name}: ${message}\n`
if (stack.startsWith(expectedPrefix)) {
return stack.slice(expectedPrefix.length)
}
return stack
}
/**
* Esbuild code frames have newlines at the start and end of the frame, rollup doesn't
* This function normalizes the frame to match the esbuild format which has more pleasing padding
*/
const normalizeCodeFrame = (frame: string) => {
const trimmedPadding = frame.replace(/^\n|\n$/g, '')
return `\n${trimmedPadding}\n`
}
const enhanceRollupError = (e: RollupError) => {
const stackOnly = extractStack(e)
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(normalizeCodeFrame(e.frame))
}
e.message = msg
// We are rebuilding the stack trace to include the more detailed message at the top.
// Previously this code was relying on mutating e.message changing the generated stack
// when it was accessed, but we don't have any guarantees that the error we are working
// with hasn't already had its stack accessed before we get here.
if (stackOnly !== undefined) {
e.stack = `${e.message}\n${stackOnly}`
}
}
const outputBuildError = (e: RollupError) => {
enhanceRollupError(e)
clearLine()
logger.error(e.message, { error: e })
}
let bundle: RollupBuild | undefined
let startTime: number | undefined
try {
const buildOutputOptions = (output: OutputOptions = {}): OutputOptions => {
// @ts-expect-error See https://github.com/vitejs/vite/issues/5812#issuecomment-984345618
if (output.output) {
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.`,
)
}
if (output.file) {
throw new Error(
`Vite does not support "rollupOptions.output.file". ` +
`Please use "rollupOptions.output.dir" and "rollupOptions.output.entryFileNames" instead.`,
)
}
if (output.sourcemap) {
logger.warnOnce(
colors.yellow(
`Vite does not support "rollupOptions.output.sourcemap". ` +
`Please use "build.sourcemap" instead.`,
),
)
}
const format = output.format || 'es'
const jsExt =
environment.config.consumer === 'server' || libOptions
? resolveOutputJsExtension(
format,
findNearestPackageData(root, packageCache)?.data.type,
)
: 'js'
return {
dir: outDir,
// Default format is 'es' for regular and for SSR builds
format,
exports: 'auto',
sourcemap: options.sourcemap,
name: libOptions ? libOptions.name : undefined,
hoistTransitiveImports: libOptions ? false : 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,
root,
jsExt,
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',
...output,
}
}
// resolve lib mode outputs
const outputs = resolveBuildOutputs(
options.rollupOptions?.output,
libOptions,
logger,
)
const normalizedOutputs: OutputOptions[] = []
if (Array.isArray(outputs)) {
for (const resolvedOutput of outputs) {
normalizedOutputs.push(buildOutputOptions(resolvedOutput))
}
} else {
normalizedOutputs.push(buildOutputOptions(outputs))
}
const resolvedOutDirs = getResolvedOutDirs(
root,
options.outDir,
options.rollupOptions?.output,
)
const emptyOutDir = resolveEmptyOutDir(
options.emptyOutDir,
root,
resolvedOutDirs,
logger,
)
// watch file changes with rollup
if (options.watch) {
logger.info(colors.cyan(`\nwatching for file changes...`))
const resolvedChokidarOptions = resolveChokidarOptions(
options.watch.chokidar,
resolvedOutDirs,
emptyOutDir,
environment.config.cacheDir,
)
const { watch } = await import('rollup')
const watcher = watch({
...rollupOptions,
output: normalizedOutputs,
watch: {
...options.watch,
chokidar: resolvedChokidarOptions,
},
})
watcher.on('event', (event) => {
if (event.code === 'BUNDLE_START') {
logger.info(colors.cyan(`\nbuild started...`))
if (options.write) {
prepareOutDir(resolvedOutDirs, emptyOutDir, environment)
}
} else if (event.code === 'BUNDLE_END') {
event.result.close()
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')
startTime = Date.now()
bundle = await rollup(rollupOptions)
if (options.write) {
prepareOutDir(resolvedOutDirs, emptyOutDir, environment)
}
const res: RollupOutput[] = []
for (const output of normalizedOutputs) {
res.push(await bundle[options.write ? 'write' : 'generate'](output))
}
logger.info(
`${colors.green(`✓ built in ${displayTime(Date.now() - startTime)}`)}`,
)
return Array.isArray(outputs) ? res : res[0]
} catch (e) {
enhanceRollupError(e)
clearLine()
if (startTime) {
logger.error(
`${colors.red('x')} Build failed in ${displayTime(Date.now() - startTime)}`,
)
startTime = undefined
}
throw e
} finally {
if (bundle) await bundle.close()
}
}
function prepareOutDir(
outDirs: Set<string>,
emptyOutDir: boolean | null,
environment: BuildEnvironment,
) {
const { publicDir } = environment.config
const outDirsArray = [...outDirs]
for (const outDir of outDirs) {
if (emptyOutDir !== false && fs.existsSync(outDir)) {
// skip those other outDirs which are nested in current outDir
const skipDirs = outDirsArray
.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 (
environment.config.build.copyPublicDir &&
publicDir &&
fs.existsSync(publicDir)
) {
if (!areSeparateFolders(outDir, publicDir)) {
environment.logger.warn(
colors.yellow(
`\n${colors.bold(
`(!)`,
)} The public directory feature may not work correctly. outDir ${colors.white(
colors.dim(outDir),
)} and publicDir ${colors.white(
colors.dim(publicDir),
)} are not separate folders.\n`,
),
)
}
copyDir(publicDir, outDir)
}
}
}
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 (
(output.format === 'umd' || output.format === 'iife') &&
!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 = [