-
-
Notifications
You must be signed in to change notification settings - Fork 6.3k
/
Copy pathindex.ts
1362 lines (1234 loc) · 40.5 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
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 fsp from 'node:fs/promises'
import path from 'node:path'
import { promisify } from 'node:util'
import { performance } from 'node:perf_hooks'
import colors from 'picocolors'
import type { BuildContext, BuildOptions as EsbuildBuildOptions } from 'esbuild'
import esbuild, { build } from 'esbuild'
import { init, parse } from 'es-module-lexer'
import glob from 'fast-glob'
import { createFilter } from '@rollup/pluginutils'
import { getDepOptimizationConfig } from '../config'
import type { ResolvedConfig } from '../config'
import {
arraify,
createDebugger,
flattenId,
getHash,
isOptimizable,
isWindows,
lookupFile,
normalizeId,
normalizePath,
removeLeadingSlash,
tryStatSync,
} from '../utils'
import { transformWithEsbuild } from '../plugins/esbuild'
import { ESBUILD_MODULES_TARGET } from '../constants'
import { esbuildCjsExternalPlugin, esbuildDepPlugin } from './esbuildDepPlugin'
import { scanImports } from './scan'
import { createOptimizeDepsIncludeResolver, expandGlobIds } from './resolve'
export {
initDepsOptimizer,
initDevSsrDepsOptimizer,
getDepsOptimizer,
} from './optimizer'
const debug = createDebugger('vite:deps')
const jsExtensionRE = /\.js$/i
const jsMapExtensionRE = /\.js\.map$/i
export type ExportsData = {
hasImports: boolean
// exported names (for `export { a as b }`, `b` is exported name)
exports: readonly string[]
// hint if the dep requires loading as jsx
jsxLoader?: boolean
}
export interface DepsOptimizer {
metadata: DepOptimizationMetadata
scanProcessing?: Promise<void>
registerMissingImport: (id: string, resolved: string) => OptimizedDepInfo
run: () => void
isOptimizedDepFile: (id: string) => boolean
isOptimizedDepUrl: (url: string) => boolean
getOptimizedDepId: (depInfo: OptimizedDepInfo) => string
delayDepsOptimizerUntil: (id: string, done: () => Promise<any>) => void
registerWorkersSource: (id: string) => void
resetRegisteredIds: () => void
ensureFirstRun: () => void
close: () => Promise<void>
options: DepOptimizationOptions
}
export interface DepOptimizationConfig {
/**
* Force optimize listed dependencies (must be resolvable import paths,
* cannot be globs).
*/
include?: string[]
/**
* Do not optimize these dependencies (must be resolvable import paths,
* cannot be globs).
*/
exclude?: string[]
/**
* Forces ESM interop when importing these dependencies. Some legacy
* packages advertise themselves as ESM but use `require` internally
* @experimental
*/
needsInterop?: string[]
/**
* Options to pass to esbuild during the dep scanning and optimization
*
* Certain options are omitted since changing them would not be compatible
* with Vite's dep optimization.
*
* - `external` is also omitted, use Vite's `optimizeDeps.exclude` option
* - `plugins` are merged with Vite's dep plugin
*
* https://esbuild.github.io/api
*/
esbuildOptions?: Omit<
EsbuildBuildOptions,
| 'bundle'
| 'entryPoints'
| 'external'
| 'write'
| 'watch'
| 'outdir'
| 'outfile'
| 'outbase'
| 'outExtension'
| 'metafile'
>
/**
* List of file extensions that can be optimized. A corresponding esbuild
* plugin must exist to handle the specific extension.
*
* By default, Vite can optimize `.mjs`, `.js`, `.ts`, and `.mts` files. This option
* allows specifying additional extensions.
*
* @experimental
*/
extensions?: string[]
/**
* Disables dependencies optimizations, true disables the optimizer during
* build and dev. Pass 'build' or 'dev' to only disable the optimizer in
* one of the modes. Deps optimization is enabled by default in dev only.
* @default 'build'
* @experimental
*/
disabled?: boolean | 'build' | 'dev'
/**
* Automatic dependency discovery. When `noDiscovery` is true, only dependencies
* listed in `include` will be optimized. The scanner isn't run for cold start
* in this case. CJS-only dependencies must be present in `include` during dev.
* @default false
* @experimental
*/
noDiscovery?: boolean
}
export type DepOptimizationOptions = DepOptimizationConfig & {
/**
* By default, Vite will crawl your `index.html` to detect dependencies that
* need to be pre-bundled. If `build.rollupOptions.input` is specified, Vite
* will crawl those entry points instead.
*
* If neither of these fit your needs, you can specify custom entries using
* this option - the value should be a fast-glob pattern or array of patterns
* (https://github.com/mrmlnc/fast-glob#basic-syntax) that are relative from
* vite project root. This will overwrite default entries inference.
*/
entries?: string | string[]
/**
* Force dep pre-optimization regardless of whether deps have changed.
* @experimental
*/
force?: boolean
}
export interface DepOptimizationResult {
metadata: DepOptimizationMetadata
/**
* When doing a re-run, if there are newly discovered dependencies
* the page reload will be delayed until the next rerun so we need
* to be able to discard the result
*/
commit: () => Promise<void>
cancel: () => void
}
export interface DepOptimizationProcessing {
promise: Promise<void>
resolve: () => void
}
export interface OptimizedDepInfo {
id: string
file: string
src?: string
needsInterop?: boolean
browserHash?: string
fileHash?: string
/**
* During optimization, ids can still be resolved to their final location
* but the bundles may not yet be saved to disk
*/
processing?: Promise<void>
/**
* ExportData cache, discovered deps will parse the src entry to get exports
* data used both to define if interop is needed and when pre-bundling
*/
exportsData?: Promise<ExportsData>
}
export interface DepOptimizationMetadata {
/**
* The main hash is determined by user config and dependency lockfiles.
* This is checked on server startup to avoid unnecessary re-bundles.
*/
hash: string
/**
* The browser hash is determined by the main hash plus additional dependencies
* discovered at runtime. This is used to invalidate browser requests to
* optimized deps.
*/
browserHash: string
/**
* Metadata for each already optimized dependency
*/
optimized: Record<string, OptimizedDepInfo>
/**
* Metadata for non-entry optimized chunks and dynamic imports
*/
chunks: Record<string, OptimizedDepInfo>
/**
* Metadata for each newly discovered dependency after processing
*/
discovered: Record<string, OptimizedDepInfo>
/**
* OptimizedDepInfo list
*/
depInfoList: OptimizedDepInfo[]
}
/**
* Scan and optimize dependencies within a project.
* Used by Vite CLI when running `vite optimize`.
*/
export async function optimizeDeps(
config: ResolvedConfig,
force = config.optimizeDeps.force,
asCommand = false,
): Promise<DepOptimizationMetadata> {
const log = asCommand ? config.logger.info : debug
const ssr = config.command === 'build' && !!config.build.ssr
const cachedMetadata = await loadCachedDepOptimizationMetadata(
config,
ssr,
force,
asCommand,
)
if (cachedMetadata) {
return cachedMetadata
}
const deps = await discoverProjectDependencies(config).result
const depsString = depsLogString(Object.keys(deps))
log?.(colors.green(`Optimizing dependencies:\n ${depsString}`))
await addManuallyIncludedOptimizeDeps(deps, config, ssr)
const depsInfo = toDiscoveredDependencies(config, deps, ssr)
const result = await runOptimizeDeps(config, depsInfo).result
await result.commit()
return result.metadata
}
export async function optimizeServerSsrDeps(
config: ResolvedConfig,
): Promise<DepOptimizationMetadata> {
const ssr = true
const cachedMetadata = await loadCachedDepOptimizationMetadata(
config,
ssr,
config.optimizeDeps.force,
false,
)
if (cachedMetadata) {
return cachedMetadata
}
let alsoInclude: string[] | undefined
let noExternalFilter: ((id: unknown) => boolean) | undefined
const { exclude } = getDepOptimizationConfig(config, ssr)
const noExternal = config.ssr?.noExternal
if (noExternal) {
alsoInclude = arraify(noExternal).filter(
(ne) => typeof ne === 'string',
) as string[]
noExternalFilter =
noExternal === true
? (dep: unknown) => true
: createFilter(undefined, exclude, {
resolve: false,
})
}
const deps: Record<string, string> = {}
await addManuallyIncludedOptimizeDeps(
deps,
config,
ssr,
alsoInclude,
noExternalFilter,
)
const depsInfo = toDiscoveredDependencies(config, deps, true)
const result = await runOptimizeDeps(config, depsInfo, true).result
await result.commit()
return result.metadata
}
export function initDepsOptimizerMetadata(
config: ResolvedConfig,
ssr: boolean,
timestamp?: string,
): DepOptimizationMetadata {
const hash = getDepHash(config, ssr)
return {
hash,
browserHash: getOptimizedBrowserHash(hash, {}, timestamp),
optimized: {},
chunks: {},
discovered: {},
depInfoList: [],
}
}
export function addOptimizedDepInfo(
metadata: DepOptimizationMetadata,
type: 'optimized' | 'discovered' | 'chunks',
depInfo: OptimizedDepInfo,
): OptimizedDepInfo {
metadata[type][depInfo.id] = depInfo
metadata.depInfoList.push(depInfo)
return depInfo
}
let firstLoadCachedDepOptimizationMetadata = true
/**
* Creates the initial dep optimization metadata, loading it from the deps cache
* if it exists and pre-bundling isn't forced
*/
export async function loadCachedDepOptimizationMetadata(
config: ResolvedConfig,
ssr: boolean,
force = config.optimizeDeps.force,
asCommand = false,
): Promise<DepOptimizationMetadata | undefined> {
const log = asCommand ? config.logger.info : debug
if (firstLoadCachedDepOptimizationMetadata) {
firstLoadCachedDepOptimizationMetadata = false
// Fire up a clean up of stale processing deps dirs if older process exited early
setTimeout(() => cleanupDepsCacheStaleDirs(config), 0)
}
const depsCacheDir = getDepsCacheDir(config, ssr)
if (!force) {
let cachedMetadata: DepOptimizationMetadata | undefined
try {
const cachedMetadataPath = path.join(depsCacheDir, '_metadata.json')
cachedMetadata = parseDepsOptimizerMetadata(
await fsp.readFile(cachedMetadataPath, 'utf-8'),
depsCacheDir,
)
} catch (e) {}
// hash is consistent, no need to re-bundle
if (cachedMetadata && cachedMetadata.hash === getDepHash(config, ssr)) {
log?.('Hash is consistent. Skipping. Use --force to override.')
// Nothing to commit or cancel as we are using the cache, we only
// need to resolve the processing promise so requests can move on
return cachedMetadata
}
} else {
config.logger.info('Forced re-optimization of dependencies')
}
// Start with a fresh cache
await fsp.rm(depsCacheDir, { recursive: true, force: true })
}
/**
* Initial optimizeDeps at server start. Perform a fast scan using esbuild to
* find deps to pre-bundle and include user hard-coded dependencies
*/
export function discoverProjectDependencies(config: ResolvedConfig): {
cancel: () => Promise<void>
result: Promise<Record<string, string>>
} {
const { cancel, result } = scanImports(config)
return {
cancel,
result: result.then(({ deps, missing }) => {
const missingIds = Object.keys(missing)
if (missingIds.length) {
throw new Error(
`The following dependencies are imported but could not be resolved:\n\n ${missingIds
.map(
(id) =>
`${colors.cyan(id)} ${colors.white(
colors.dim(`(imported by ${missing[id]})`),
)}`,
)
.join(`\n `)}\n\nAre they installed?`,
)
}
return deps
}),
}
}
export function toDiscoveredDependencies(
config: ResolvedConfig,
deps: Record<string, string>,
ssr: boolean,
timestamp?: string,
): Record<string, OptimizedDepInfo> {
const browserHash = getOptimizedBrowserHash(
getDepHash(config, ssr),
deps,
timestamp,
)
const discovered: Record<string, OptimizedDepInfo> = {}
for (const id in deps) {
const src = deps[id]
discovered[id] = {
id,
file: getOptimizedDepPath(id, config, ssr),
src,
browserHash: browserHash,
exportsData: extractExportsData(src, config, ssr),
}
}
return discovered
}
export function depsLogString(qualifiedIds: string[]): string {
return colors.yellow(qualifiedIds.join(`, `))
}
/**
* Internally, Vite uses this function to prepare a optimizeDeps run. When Vite starts, we can get
* the metadata and start the server without waiting for the optimizeDeps processing to be completed
*/
export function runOptimizeDeps(
resolvedConfig: ResolvedConfig,
depsInfo: Record<string, OptimizedDepInfo>,
ssr: boolean = resolvedConfig.command === 'build' &&
!!resolvedConfig.build.ssr,
): {
cancel: () => Promise<void>
result: Promise<DepOptimizationResult>
} {
const optimizerContext = { cancelled: false }
const config: ResolvedConfig = {
...resolvedConfig,
command: 'build',
}
const depsCacheDir = getDepsCacheDir(resolvedConfig, ssr)
const processingCacheDir = getProcessingDepsCacheDir(resolvedConfig, ssr)
// Create a temporal directory so we don't need to delete optimized deps
// until they have been processed. This also avoids leaving the deps cache
// directory in a corrupted state if there is an error
fs.mkdirSync(processingCacheDir, { recursive: true })
// a hint for Node.js
// all files in the cache directory should be recognized as ES modules
fs.writeFileSync(
path.resolve(processingCacheDir, 'package.json'),
`{\n "type": "module"\n}\n`,
)
const metadata = initDepsOptimizerMetadata(config, ssr)
metadata.browserHash = getOptimizedBrowserHash(
metadata.hash,
depsFromOptimizedDepInfo(depsInfo),
)
// We prebundle dependencies with esbuild and cache them, but there is no need
// to wait here. Code that needs to access the cached deps needs to await
// the optimizedDepInfo.processing promise for each dep
const qualifiedIds = Object.keys(depsInfo)
let cleaned = false
let committed = false
const cleanUp = () => {
// If commit was already called, ignore the clean up even if a cancel was requested
// This minimizes the chances of leaving the deps cache in a corrupted state
if (!cleaned && !committed) {
cleaned = true
// No need to wait, we can clean up in the background because temp folders
// are unique per run
fsp.rm(processingCacheDir, { recursive: true, force: true }).catch(() => {
// Ignore errors
})
}
}
const succesfulResult: DepOptimizationResult = {
metadata,
cancel: cleanUp,
commit: async () => {
if (cleaned) {
throw new Error(
'Can not commit a Deps Optimization run as it was cancelled',
)
}
// Ignore clean up requests after this point so the temp folder isn't deleted before
// we finish commiting the new deps cache files to the deps folder
committed = true
// Write metadata file, then commit the processing folder to the global deps cache
// Rewire the file paths from the temporal processing dir to the final deps cache dir
const dataPath = path.join(processingCacheDir, '_metadata.json')
fs.writeFileSync(
dataPath,
stringifyDepsOptimizerMetadata(metadata, depsCacheDir),
)
// In order to minimize the time where the deps folder isn't in a consistent state,
// we first rename the old depsCacheDir to a temporal path, then we rename the
// new processing cache dir to the depsCacheDir. In systems where doing so in sync
// is safe, we do an atomic operation (at least for this thread). For Windows, we
// found there are cases where the rename operation may finish before it's done
// so we do a graceful rename checking that the folder has been properly renamed.
// We found that the rename-rename (then delete the old folder in the background)
// is safer than a delete-rename operation.
const temporalPath = depsCacheDir + getTempSuffix()
const depsCacheDirPresent = fs.existsSync(depsCacheDir)
if (isWindows) {
if (depsCacheDirPresent) await safeRename(depsCacheDir, temporalPath)
await safeRename(processingCacheDir, depsCacheDir)
} else {
if (depsCacheDirPresent) fs.renameSync(depsCacheDir, temporalPath)
fs.renameSync(processingCacheDir, depsCacheDir)
}
// Delete temporal path in the background
if (depsCacheDirPresent)
fsp.rm(temporalPath, { recursive: true, force: true })
},
}
if (!qualifiedIds.length) {
// No deps to optimize, we still commit the processing cache dir to remove
// the previous optimized deps if they exist, and let the next server start
// skip the scanner step if the lockfile hasn't changed
return {
cancel: async () => cleanUp(),
result: Promise.resolve(succesfulResult),
}
}
const cancelledResult: DepOptimizationResult = {
metadata,
commit: async () => cleanUp(),
cancel: cleanUp,
}
const start = performance.now()
const preparedRun = prepareEsbuildOptimizerRun(
resolvedConfig,
depsInfo,
ssr,
processingCacheDir,
optimizerContext,
)
const runResult = preparedRun.then(({ context, idToExports }) => {
function disposeContext() {
return context?.dispose().catch((e) => {
config.logger.error('Failed to dispose esbuild context', { error: e })
})
}
if (!context || optimizerContext.cancelled) {
disposeContext()
return cancelledResult
}
return context
.rebuild()
.then((result) => {
const meta = result.metafile!
// the paths in `meta.outputs` are relative to `process.cwd()`
const processingCacheDirOutputPath = path.relative(
process.cwd(),
processingCacheDir,
)
for (const id in depsInfo) {
const output = esbuildOutputFromId(
meta.outputs,
id,
processingCacheDir,
)
const { exportsData, ...info } = depsInfo[id]
addOptimizedDepInfo(metadata, 'optimized', {
...info,
// We only need to hash the output.imports in to check for stability, but adding the hash
// and file path gives us a unique hash that may be useful for other things in the future
fileHash: getHash(
metadata.hash +
depsInfo[id].file +
JSON.stringify(output.imports),
),
browserHash: metadata.browserHash,
// After bundling we have more information and can warn the user about legacy packages
// that require manual configuration
needsInterop: needsInterop(
config,
ssr,
id,
idToExports[id],
output,
),
})
}
for (const o of Object.keys(meta.outputs)) {
if (!o.match(jsMapExtensionRE)) {
const id = path
.relative(processingCacheDirOutputPath, o)
.replace(jsExtensionRE, '')
const file = getOptimizedDepPath(id, resolvedConfig, ssr)
if (
!findOptimizedDepInfoInRecord(
metadata.optimized,
(depInfo) => depInfo.file === file,
)
) {
addOptimizedDepInfo(metadata, 'chunks', {
id,
file,
needsInterop: false,
browserHash: metadata.browserHash,
})
}
}
}
debug?.(
`Dependencies bundled in ${(performance.now() - start).toFixed(2)}ms`,
)
return succesfulResult
})
.catch((e) => {
if (e.errors && e.message.includes('The build was canceled')) {
// esbuild logs an error when cancelling, but this is expected so
// return an empty result instead
return cancelledResult
}
throw e
})
.finally(() => {
return disposeContext()
})
})
runResult.catch(() => {
cleanUp()
})
return {
async cancel() {
optimizerContext.cancelled = true
const { context } = await preparedRun
await context?.cancel()
cleanUp()
},
result: runResult,
}
}
async function prepareEsbuildOptimizerRun(
resolvedConfig: ResolvedConfig,
depsInfo: Record<string, OptimizedDepInfo>,
ssr: boolean,
processingCacheDir: string,
optimizerContext: { cancelled: boolean },
): Promise<{
context?: BuildContext
idToExports: Record<string, ExportsData>
}> {
const isBuild = resolvedConfig.command === 'build'
const config: ResolvedConfig = {
...resolvedConfig,
command: 'build',
}
// esbuild generates nested directory output with lowest common ancestor base
// this is unpredictable and makes it difficult to analyze entry / output
// mapping. So what we do here is:
// 1. flatten all ids to eliminate slash
// 2. in the plugin, read the entry ourselves as virtual files to retain the
// path.
const flatIdDeps: Record<string, string> = {}
const idToExports: Record<string, ExportsData> = {}
const flatIdToExports: Record<string, ExportsData> = {}
const optimizeDeps = getDepOptimizationConfig(config, ssr)
const { plugins: pluginsFromConfig = [], ...esbuildOptions } =
optimizeDeps?.esbuildOptions ?? {}
await Promise.all(
Object.keys(depsInfo).map(async (id) => {
const src = depsInfo[id].src!
const exportsData = await (depsInfo[id].exportsData ??
extractExportsData(src, config, ssr))
if (exportsData.jsxLoader && !esbuildOptions.loader?.['.js']) {
// Ensure that optimization won't fail by defaulting '.js' to the JSX parser.
// This is useful for packages such as Gatsby.
esbuildOptions.loader = {
'.js': 'jsx',
...esbuildOptions.loader,
}
}
const flatId = flattenId(id)
flatIdDeps[flatId] = src
idToExports[id] = exportsData
flatIdToExports[flatId] = exportsData
}),
)
if (optimizerContext.cancelled) return { context: undefined, idToExports }
// esbuild automatically replaces process.env.NODE_ENV for platform 'browser'
// In lib mode, we need to keep process.env.NODE_ENV untouched, so to at build
// time we replace it by __vite_process_env_NODE_ENV. This placeholder will be
// later replaced by the define plugin
const define = {
'process.env.NODE_ENV': isBuild
? '__vite_process_env_NODE_ENV'
: JSON.stringify(process.env.NODE_ENV || config.mode),
}
const platform =
ssr && config.ssr?.target !== 'webworker' ? 'node' : 'browser'
const external = [...(optimizeDeps?.exclude ?? [])]
if (isBuild) {
let rollupOptionsExternal = config?.build?.rollupOptions?.external
if (rollupOptionsExternal) {
if (typeof rollupOptionsExternal === 'string') {
rollupOptionsExternal = [rollupOptionsExternal]
}
// TODO: decide whether to support RegExp and function options
// They're not supported yet because `optimizeDeps.exclude` currently only accepts strings
if (
!Array.isArray(rollupOptionsExternal) ||
rollupOptionsExternal.some((ext) => typeof ext !== 'string')
) {
throw new Error(
`[vite] 'build.rollupOptions.external' can only be an array of strings or a string when using esbuild optimization at build time.`,
)
}
external.push(...(rollupOptionsExternal as string[]))
}
}
const plugins = [...pluginsFromConfig]
if (external.length) {
plugins.push(esbuildCjsExternalPlugin(external, platform))
}
plugins.push(esbuildDepPlugin(flatIdDeps, external, config, ssr))
const context = await esbuild.context({
absWorkingDir: process.cwd(),
entryPoints: Object.keys(flatIdDeps),
bundle: true,
// We can't use platform 'neutral', as esbuild has custom handling
// when the platform is 'node' or 'browser' that can't be emulated
// by using mainFields and conditions
platform,
define,
format: 'esm',
// See https://github.com/evanw/esbuild/issues/1921#issuecomment-1152991694
banner:
platform === 'node'
? {
js: `import { createRequire } from 'module';const require = createRequire(import.meta.url);`,
}
: undefined,
target: isBuild ? config.build.target || undefined : ESBUILD_MODULES_TARGET,
external,
logLevel: 'error',
splitting: true,
sourcemap: true,
outdir: processingCacheDir,
ignoreAnnotations: !isBuild,
metafile: true,
plugins,
charset: 'utf8',
...esbuildOptions,
supported: {
'dynamic-import': true,
'import-meta': true,
...esbuildOptions.supported,
},
})
return { context, idToExports }
}
export async function findKnownImports(
config: ResolvedConfig,
ssr: boolean,
): Promise<string[]> {
const { deps } = await scanImports(config).result
await addManuallyIncludedOptimizeDeps(deps, config, ssr)
return Object.keys(deps)
}
export async function addManuallyIncludedOptimizeDeps(
deps: Record<string, string>,
config: ResolvedConfig,
ssr: boolean,
extra: string[] = [],
filter?: (id: string) => boolean,
): Promise<void> {
const { logger } = config
const optimizeDeps = getDepOptimizationConfig(config, ssr)
const optimizeDepsInclude = optimizeDeps?.include ?? []
if (optimizeDepsInclude.length || extra.length) {
const unableToOptimize = (id: string, msg: string) => {
if (optimizeDepsInclude.includes(id)) {
logger.warn(
`${msg}: ${colors.cyan(id)}, present in '${
ssr ? 'ssr.' : ''
}optimizeDeps.include'`,
)
}
}
const includes = [...optimizeDepsInclude, ...extra]
for (let i = 0; i < includes.length; i++) {
const id = includes[i]
if (glob.isDynamicPattern(id)) {
const globIds = expandGlobIds(id, config)
includes.splice(i, 1, ...globIds)
i += globIds.length - 1
}
}
const resolve = createOptimizeDepsIncludeResolver(config, ssr)
for (const id of includes) {
// normalize 'foo >bar` as 'foo > bar' to prevent same id being added
// and for pretty printing
const normalizedId = normalizeId(id)
if (!deps[normalizedId] && filter?.(normalizedId) !== false) {
const entry = await resolve(id)
if (entry) {
if (isOptimizable(entry, optimizeDeps)) {
if (!entry.endsWith('?__vite_skip_optimization')) {
deps[normalizedId] = entry
}
} else {
unableToOptimize(id, 'Cannot optimize dependency')
}
} else {
unableToOptimize(id, 'Failed to resolve dependency')
}
}
}
}
}
export function newDepOptimizationProcessing(): DepOptimizationProcessing {
let resolve: () => void
const promise = new Promise((_resolve) => {
resolve = _resolve
}) as Promise<void>
return { promise, resolve: resolve! }
}
// Convert to { id: src }
export function depsFromOptimizedDepInfo(
depsInfo: Record<string, OptimizedDepInfo>,
): Record<string, string> {
return Object.fromEntries(
Object.entries(depsInfo).map((d) => [d[0], d[1].src!]),
)
}
export function getOptimizedDepPath(
id: string,
config: ResolvedConfig,
ssr: boolean,
): string {
return normalizePath(
path.resolve(getDepsCacheDir(config, ssr), flattenId(id) + '.js'),
)
}
function getDepsCacheSuffix(config: ResolvedConfig, ssr: boolean): string {
let suffix = ''
if (config.command === 'build') {
// Differentiate build caches depending on outDir to allow parallel builds
const { outDir } = config.build
const buildId =
outDir.length > 8 || outDir.includes('/') ? getHash(outDir) : outDir
suffix += `_build-${buildId}`
}
if (ssr) {
suffix += '_ssr'
}
return suffix
}
export function getDepsCacheDir(config: ResolvedConfig, ssr: boolean): string {
return getDepsCacheDirPrefix(config) + getDepsCacheSuffix(config, ssr)
}
function getProcessingDepsCacheDir(config: ResolvedConfig, ssr: boolean) {
return (
getDepsCacheDirPrefix(config) +
getDepsCacheSuffix(config, ssr) +
getTempSuffix()
)
}
function getTempSuffix() {
return (
'_temp_' +
getHash(
`${process.pid}:${Date.now().toString()}:${Math.random()
.toString(16)
.slice(2)}`,
)
)
}
function getDepsCacheDirPrefix(config: ResolvedConfig): string {
return normalizePath(path.resolve(config.cacheDir, 'deps'))
}
export function createIsOptimizedDepFile(
config: ResolvedConfig,
): (id: string) => boolean {
const depsCacheDirPrefix = getDepsCacheDirPrefix(config)
return (id) => id.startsWith(depsCacheDirPrefix)
}
export function createIsOptimizedDepUrl(
config: ResolvedConfig,
): (url: string) => boolean {
const { root } = config
const depsCacheDir = getDepsCacheDirPrefix(config)
// determine the url prefix of files inside cache directory
const depsCacheDirRelative = normalizePath(path.relative(root, depsCacheDir))
const depsCacheDirPrefix = depsCacheDirRelative.startsWith('../')
? // if the cache directory is outside root, the url prefix would be something
// like '/@fs/absolute/path/to/node_modules/.vite'
`/@fs/${removeLeadingSlash(normalizePath(depsCacheDir))}`
: // if the cache directory is inside root, the url prefix would be something
// like '/node_modules/.vite'
`/${depsCacheDirRelative}`
return function isOptimizedDepUrl(url: string): boolean {
return url.startsWith(depsCacheDirPrefix)
}
}
function parseDepsOptimizerMetadata(
jsonMetadata: string,
depsCacheDir: string,
): DepOptimizationMetadata | undefined {
const { hash, browserHash, optimized, chunks } = JSON.parse(
jsonMetadata,
(key: string, value: string) => {
// Paths can be absolute or relative to the deps cache dir where
// the _metadata.json is located
if (key === 'file' || key === 'src') {
return normalizePath(path.resolve(depsCacheDir, value))
}
return value
},
)
if (
!chunks ||
Object.values(optimized).some((depInfo: any) => !depInfo.fileHash)
) {
// outdated _metadata.json version, ignore
return
}