-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
Copy pathresolve.ts
1335 lines (1210 loc) · 37.3 KB
/
resolve.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 { PartialResolvedId } from 'rollup'
import { exports, imports } from 'resolve.exports'
import { hasESMSyntax } from 'mlly'
import type { Plugin } from '../plugin'
import {
CLIENT_ENTRY,
DEFAULT_EXTENSIONS,
DEFAULT_MAIN_FIELDS,
DEP_VERSION_RE,
ENV_ENTRY,
FS_PREFIX,
OPTIMIZABLE_ENTRY_RE,
SPECIAL_QUERY_RE,
} from '../constants'
import {
bareImportRE,
cleanUrl,
createDebugger,
ensureVolumeInPath,
fsPathFromId,
getPotentialTsSrcPaths,
injectQuery,
isBuiltin,
isDataUrl,
isExternalUrl,
isNonDriveRelativeAbsolutePath,
isObject,
isOptimizable,
isPossibleTsOutput,
isTsRequest,
isWindows,
lookupFile,
normalizePath,
resolveFrom,
slash,
} from '../utils'
import { optimizedDepInfoFromFile, optimizedDepInfoFromId } from '../optimizer'
import type { DepsOptimizer } from '../optimizer'
import type { SSROptions } from '..'
import type { PackageCache, PackageData } from '../packages'
import { loadPackageData, resolvePackageData } from '../packages'
import { isWorkerRequest } from './worker'
const normalizedClientEntry = normalizePath(CLIENT_ENTRY)
const normalizedEnvEntry = normalizePath(ENV_ENTRY)
// special id for paths marked with browser: false
// https://github.com/defunctzombie/package-browser-field-spec#ignore-a-module
export const browserExternalId = '__vite-browser-external'
// special id for packages that are optional peer deps
export const optionalPeerDepId = '__vite-optional-peer-dep'
const nodeModulesInPathRE = /(?:^|\/)node_modules\//
const subpathImportsPrefix = '#'
const isDebug = process.env.DEBUG
const debug = createDebugger('vite:resolve-details', {
onlyWhenFocused: true,
})
export interface ResolveOptions {
/**
* @default ['module', 'jsnext:main', 'jsnext']
*/
mainFields?: string[]
/**
* @deprecated In future, `mainFields` should be used instead.
* @default true
*/
browserField?: boolean
conditions?: string[]
/**
* @default ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json']
*/
extensions?: string[]
dedupe?: string[]
/**
* @default false
*/
preserveSymlinks?: boolean
}
export interface InternalResolveOptions extends Required<ResolveOptions> {
root: string
isBuild: boolean
isProduction: boolean
ssrConfig?: SSROptions
packageCache?: PackageCache
/**
* src code mode also attempts the following:
* - resolving /xxx as URLs
* - resolving bare imports from optimized deps
*/
asSrc?: boolean
tryIndex?: boolean
tryPrefix?: string
skipPackageJson?: boolean
preferRelative?: boolean
isRequire?: boolean
// #3040
// when the importer is a ts module,
// if the specifier requests a non-existent `.js/jsx/mjs/cjs` file,
// should also try import from `.ts/tsx/mts/cts` source file as fallback.
isFromTsImporter?: boolean
tryEsmOnly?: boolean
// True when resolving during the scan phase to discover dependencies
scan?: boolean
// Appends ?__vite_skip_optimization to the resolved id if shouldn't be optimized
ssrOptimizeCheck?: boolean
// Resolve using esbuild deps optimization
getDepsOptimizer?: (ssr: boolean) => DepsOptimizer | undefined
shouldExternalize?: (id: string) => boolean | undefined
}
export function resolvePlugin(resolveOptions: InternalResolveOptions): Plugin {
const {
root,
isProduction,
asSrc,
ssrConfig,
preferRelative = false,
} = resolveOptions
const { target: ssrTarget, noExternal: ssrNoExternal } = ssrConfig ?? {}
return {
name: 'vite:resolve',
async resolveId(id, importer, resolveOpts) {
const ssr = resolveOpts?.ssr === true
// We need to delay depsOptimizer until here instead of passing it as an option
// the resolvePlugin because the optimizer is created on server listen during dev
const depsOptimizer = resolveOptions.getDepsOptimizer?.(ssr)
if (id.startsWith(browserExternalId)) {
return id
}
const targetWeb = !ssr || ssrTarget === 'webworker'
// this is passed by @rollup/plugin-commonjs
const isRequire: boolean =
resolveOpts?.custom?.['node-resolve']?.isRequire ?? false
const options: InternalResolveOptions = {
isRequire,
...resolveOptions,
scan: resolveOpts?.scan ?? resolveOptions.scan,
}
const resolveSubpathImports = (id: string, importer?: string) => {
if (!importer || !id.startsWith(subpathImportsPrefix)) return
const basedir = path.dirname(importer)
const pkgJsonPath = lookupFile(basedir, ['package.json'], {
pathOnly: true,
})
if (!pkgJsonPath) return
const pkgData = loadPackageData(pkgJsonPath, options.preserveSymlinks)
let importsPath = resolveExportsOrImports(
pkgData.data,
id,
options,
targetWeb,
'imports',
)
if (importsPath?.startsWith('.')) {
importsPath = path.relative(
basedir,
path.join(path.dirname(pkgJsonPath), importsPath),
)
if (!importsPath.startsWith('.')) {
importsPath = `./${importsPath}`
}
}
return importsPath
}
const resolvedImports = resolveSubpathImports(id, importer)
if (resolvedImports) {
id = resolvedImports
}
if (importer) {
const _importer = isWorkerRequest(importer)
? splitFileAndPostfix(importer).file
: importer
if (
isTsRequest(_importer) ||
resolveOpts.custom?.depScan?.loader?.startsWith('ts')
) {
options.isFromTsImporter = true
} else {
const moduleLang = this.getModuleInfo(_importer)?.meta?.vite?.lang
options.isFromTsImporter = moduleLang && isTsRequest(`.${moduleLang}`)
}
}
let res: string | PartialResolvedId | undefined
// resolve pre-bundled deps requests, these could be resolved by
// tryFileResolve or /fs/ resolution but these files may not yet
// exists if we are in the middle of a deps re-processing
if (asSrc && depsOptimizer?.isOptimizedDepUrl(id)) {
const optimizedPath = id.startsWith(FS_PREFIX)
? fsPathFromId(id)
: normalizePath(ensureVolumeInPath(path.resolve(root, id.slice(1))))
return optimizedPath
}
const ensureVersionQuery = (resolved: string): string => {
if (
!options.isBuild &&
!options.scan &&
depsOptimizer &&
!(
resolved === normalizedClientEntry ||
resolved === normalizedEnvEntry
)
) {
// Ensure that direct imports of node_modules have the same version query
// as if they would have been imported through a bare import
// Use the original id to do the check as the resolved id may be the real
// file path after symlinks resolution
const isNodeModule =
nodeModulesInPathRE.test(normalizePath(id)) ||
nodeModulesInPathRE.test(normalizePath(resolved))
if (isNodeModule && !resolved.match(DEP_VERSION_RE)) {
const versionHash = depsOptimizer.metadata.browserHash
if (versionHash && isOptimizable(resolved, depsOptimizer.options)) {
resolved = injectQuery(resolved, `v=${versionHash}`)
}
}
}
return resolved
}
// explicit fs paths that starts with /@fs/*
if (asSrc && id.startsWith(FS_PREFIX)) {
const fsPath = fsPathFromId(id)
res = tryFsResolve(fsPath, options)
isDebug && debug(`[@fs] ${colors.cyan(id)} -> ${colors.dim(res)}`)
// always return here even if res doesn't exist since /@fs/ is explicit
// if the file doesn't exist it should be a 404
return ensureVersionQuery(res || fsPath)
}
// URL
// /foo -> /fs-root/foo
if (asSrc && id.startsWith('/')) {
const fsPath = path.resolve(root, id.slice(1))
if ((res = tryFsResolve(fsPath, options))) {
isDebug && debug(`[url] ${colors.cyan(id)} -> ${colors.dim(res)}`)
return ensureVersionQuery(res)
}
}
// relative
if (
id.startsWith('.') ||
((preferRelative || importer?.endsWith('.html')) && /^\w/.test(id))
) {
const basedir = importer ? path.dirname(importer) : process.cwd()
const fsPath = path.resolve(basedir, id)
// handle browser field mapping for relative imports
const normalizedFsPath = normalizePath(fsPath)
if (depsOptimizer?.isOptimizedDepFile(normalizedFsPath)) {
// Optimized files could not yet exist in disk, resolve to the full path
// Inject the current browserHash version if the path doesn't have one
if (!normalizedFsPath.match(DEP_VERSION_RE)) {
const browserHash = optimizedDepInfoFromFile(
depsOptimizer.metadata,
normalizedFsPath,
)?.browserHash
if (browserHash) {
return injectQuery(normalizedFsPath, `v=${browserHash}`)
}
}
return normalizedFsPath
}
if (
targetWeb &&
options.browserField &&
(res = tryResolveBrowserMapping(fsPath, importer, options, true))
) {
return res
}
if ((res = tryFsResolve(fsPath, options))) {
res = ensureVersionQuery(res)
isDebug &&
debug(`[relative] ${colors.cyan(id)} -> ${colors.dim(res)}`)
const pkg = importer != null && idToPkgMap.get(importer)
if (pkg) {
idToPkgMap.set(res, pkg)
return {
id: res,
moduleSideEffects: pkg.hasSideEffects(res),
}
}
return res
}
}
// drive relative fs paths (only windows)
if (isWindows && id.startsWith('/')) {
const basedir = importer ? path.dirname(importer) : process.cwd()
const fsPath = path.resolve(basedir, id)
if ((res = tryFsResolve(fsPath, options))) {
isDebug &&
debug(`[drive-relative] ${colors.cyan(id)} -> ${colors.dim(res)}`)
return ensureVersionQuery(res)
}
}
// absolute fs paths
if (
isNonDriveRelativeAbsolutePath(id) &&
(res = tryFsResolve(id, options))
) {
isDebug && debug(`[fs] ${colors.cyan(id)} -> ${colors.dim(res)}`)
return ensureVersionQuery(res)
}
// external
if (isExternalUrl(id)) {
return {
id,
external: true,
}
}
// data uri: pass through (this only happens during build and will be
// handled by dedicated plugin)
if (isDataUrl(id)) {
return null
}
// bare package imports, perform node resolve
if (bareImportRE.test(id)) {
const external = options.shouldExternalize?.(id)
if (
!external &&
asSrc &&
depsOptimizer &&
!options.scan &&
(res = await tryOptimizedResolve(depsOptimizer, id, importer))
) {
return res
}
if (
targetWeb &&
options.browserField &&
(res = tryResolveBrowserMapping(
id,
importer,
options,
false,
external,
))
) {
return res
}
if (
(res = tryNodeResolve(
id,
importer,
options,
targetWeb,
depsOptimizer,
ssr,
external,
))
) {
return res
}
// node built-ins.
// externalize if building for SSR, otherwise redirect to empty module
if (isBuiltin(id)) {
if (ssr) {
if (ssrNoExternal === true) {
let message = `Cannot bundle Node.js built-in "${id}"`
if (importer) {
message += ` imported from "${path.relative(
process.cwd(),
importer,
)}"`
}
message += `. Consider disabling ssr.noExternal or remove the built-in dependency.`
this.error(message)
}
return {
id,
external: true,
}
} else {
if (!asSrc) {
debug(
`externalized node built-in "${id}" to empty module. ` +
`(imported by: ${colors.white(colors.dim(importer))})`,
)
}
return isProduction
? browserExternalId
: `${browserExternalId}:${id}`
}
}
}
isDebug && debug(`[fallthrough] ${colors.dim(id)}`)
},
load(id) {
if (id.startsWith(browserExternalId)) {
if (isProduction) {
return `export default {}`
} else {
id = id.slice(browserExternalId.length + 1)
return `\
export default new Proxy({}, {
get(_, key) {
throw new Error(\`Module "${id}" has been externalized for browser compatibility. Cannot access "${id}.\${key}" in client code. See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\`)
}
})`
}
}
if (id.startsWith(optionalPeerDepId)) {
if (isProduction) {
return `export default {}`
} else {
const [, peerDep, parentDep] = id.split(':')
return `throw new Error(\`Could not resolve "${peerDep}" imported by "${parentDep}". Is it installed?\`)`
}
}
},
}
}
function splitFileAndPostfix(path: string) {
let file = path
let postfix = ''
let postfixIndex = path.indexOf('?')
if (postfixIndex < 0) {
postfixIndex = path.indexOf('#')
}
if (postfixIndex > 0) {
file = path.slice(0, postfixIndex)
postfix = path.slice(postfixIndex)
}
return { file, postfix }
}
function tryFsResolve(
fsPath: string,
options: InternalResolveOptions,
tryIndex = true,
targetWeb = true,
): string | undefined {
const { file, postfix } = splitFileAndPostfix(fsPath)
let res: string | undefined
// if there is a postfix, try resolving it as a complete path first (#4703)
if (
postfix &&
(res = tryResolveFile(
fsPath,
'',
options,
false,
targetWeb,
options.tryPrefix,
options.skipPackageJson,
))
) {
return res
}
if (
(res = tryResolveFile(
file,
postfix,
options,
false,
targetWeb,
options.tryPrefix,
options.skipPackageJson,
))
) {
return res
}
for (const ext of options.extensions) {
if (
postfix &&
(res = tryResolveFile(
fsPath + ext,
'',
options,
false,
targetWeb,
options.tryPrefix,
options.skipPackageJson,
false,
))
) {
return res
}
if (
(res = tryResolveFile(
file + ext,
postfix,
options,
false,
targetWeb,
options.tryPrefix,
options.skipPackageJson,
false,
))
) {
return res
}
}
// if `tryIndex` false, skip as we've already tested above
if (!tryIndex) return
if (
postfix &&
(res = tryResolveFile(
fsPath,
'',
options,
tryIndex,
targetWeb,
options.tryPrefix,
options.skipPackageJson,
))
) {
return res
}
if (
(res = tryResolveFile(
file,
postfix,
options,
tryIndex,
targetWeb,
options.tryPrefix,
options.skipPackageJson,
))
) {
return res
}
}
function tryResolveFile(
file: string,
postfix: string,
options: InternalResolveOptions,
tryIndex: boolean,
targetWeb: boolean,
tryPrefix?: string,
skipPackageJson?: boolean,
skipTsExtension?: boolean,
): string | undefined {
let stat: fs.Stats | undefined
try {
stat = fs.statSync(file, { throwIfNoEntry: false })
} catch {
return
}
if (stat) {
if (!stat.isDirectory()) {
return getRealPath(file, options.preserveSymlinks) + postfix
} else if (tryIndex) {
if (!skipPackageJson) {
const pkgPath = file + '/package.json'
try {
// path points to a node package
const pkg = loadPackageData(pkgPath, options.preserveSymlinks)
const resolved = resolvePackageEntry(file, pkg, targetWeb, options)
return resolved
} catch (e) {
if (e.code !== 'ENOENT') {
throw e
}
}
}
const index = tryFsResolve(file + '/index', options)
if (index) return index + postfix
}
}
// try resolve .js import to typescript file
if (
!skipTsExtension &&
options.isFromTsImporter &&
isPossibleTsOutput(file)
) {
const tsSrcPaths = getPotentialTsSrcPaths(file)
for (const srcPath of tsSrcPaths) {
const res = tryResolveFile(
srcPath,
postfix,
options,
tryIndex,
targetWeb,
tryPrefix,
skipPackageJson,
true,
)
if (res) return res
}
return
}
if (tryPrefix) {
const prefixed = `${path.dirname(file)}/${tryPrefix}${path.basename(file)}`
return tryResolveFile(prefixed, postfix, options, tryIndex, targetWeb)
}
}
export type InternalResolveOptionsWithOverrideConditions =
InternalResolveOptions & {
/**
* @deprecated In future, `conditions` will work like this.
* @internal
*/
overrideConditions?: string[]
}
export const idToPkgMap = new Map<string, PackageData>()
export function tryNodeResolve(
id: string,
importer: string | null | undefined,
options: InternalResolveOptionsWithOverrideConditions,
targetWeb: boolean,
depsOptimizer?: DepsOptimizer,
ssr: boolean = false,
externalize?: boolean,
allowLinkedExternal: boolean = true,
): PartialResolvedId | undefined {
const { root, dedupe, isBuild, preserveSymlinks, packageCache } = options
const possiblePkgIds: string[] = []
for (let prevSlashIndex = -1; ; ) {
let slashIndex = id.indexOf('/', prevSlashIndex + 1)
if (slashIndex < 0) {
slashIndex = id.length
}
const part = id.slice(prevSlashIndex + 1, (prevSlashIndex = slashIndex))
if (!part) {
break
}
// Assume path parts with an extension are not package roots, except for the
// first path part (since periods are sadly allowed in package names).
// At the same time, skip the first path part if it begins with "@"
// (since "@foo/bar" should be treated as the top-level path).
if (possiblePkgIds.length ? path.extname(part) : part[0] === '@') {
continue
}
const possiblePkgId = id.slice(0, slashIndex)
possiblePkgIds.push(possiblePkgId)
}
let basedir: string
if (dedupe?.some((id) => possiblePkgIds.includes(id))) {
basedir = root
} else if (
importer &&
path.isAbsolute(importer) &&
fs.existsSync(cleanUrl(importer))
) {
basedir = path.dirname(importer)
} else {
basedir = root
}
let pkg: PackageData | undefined
let pkgId: string | undefined
// nearest package.json
let nearestPkg: PackageData | undefined
const rootPkgId = possiblePkgIds[0]
const rootPkg = resolvePackageData(
rootPkgId,
basedir,
preserveSymlinks,
packageCache,
)!
const nearestPkgId = [...possiblePkgIds].reverse().find((pkgId) => {
nearestPkg = resolvePackageData(
pkgId,
basedir,
preserveSymlinks,
packageCache,
)!
return nearestPkg
})!
if (rootPkg?.data?.exports) {
pkgId = rootPkgId
pkg = rootPkg
} else {
pkgId = nearestPkgId
pkg = nearestPkg
}
if (!pkg || !nearestPkg) {
// if import can't be found, check if it's an optional peer dep.
// if so, we can resolve to a special id that errors only when imported.
if (
basedir !== root && // root has no peer dep
!isBuiltin(id) &&
!id.includes('\0') &&
bareImportRE.test(id)
) {
// find package.json with `name` as main
const mainPackageJson = lookupFile(basedir, ['package.json'], {
predicate: (content) => !!JSON.parse(content).name,
})
if (mainPackageJson) {
const mainPkg = JSON.parse(mainPackageJson)
if (
mainPkg.peerDependencies?.[id] &&
mainPkg.peerDependenciesMeta?.[id]?.optional
) {
return {
id: `${optionalPeerDepId}:${id}:${mainPkg.name}`,
}
}
}
}
return
}
let resolveId = resolvePackageEntry
let unresolvedId = pkgId
const isDeepImport = unresolvedId !== id
if (isDeepImport) {
resolveId = resolveDeepImport
unresolvedId = '.' + id.slice(pkgId.length)
}
let resolved: string | undefined
try {
resolved = resolveId(unresolvedId, pkg, targetWeb, options)
} catch (err) {
if (!options.tryEsmOnly) {
throw err
}
}
if (!resolved && options.tryEsmOnly) {
resolved = resolveId(unresolvedId, pkg, targetWeb, {
...options,
isRequire: false,
mainFields: DEFAULT_MAIN_FIELDS,
extensions: DEFAULT_EXTENSIONS,
})
}
if (!resolved) {
return
}
const processResult = (resolved: PartialResolvedId) => {
if (!externalize) {
return resolved
}
// don't external symlink packages
if (!allowLinkedExternal && !resolved.id.includes('node_modules')) {
return resolved
}
const resolvedExt = path.extname(resolved.id)
// don't external non-js imports
if (
resolvedExt &&
resolvedExt !== '.js' &&
resolvedExt !== '.mjs' &&
resolvedExt !== '.cjs'
) {
return resolved
}
let resolvedId = id
if (isDeepImport) {
if (!pkg?.data.exports && path.extname(id) !== resolvedExt) {
resolvedId = resolved.id.slice(resolved.id.indexOf(id))
isDebug &&
debug(
`[processResult] ${colors.cyan(id)} -> ${colors.dim(resolvedId)}`,
)
}
}
return { ...resolved, id: resolvedId, external: true }
}
// link id to pkg for browser field mapping check
idToPkgMap.set(resolved, pkg)
if ((isBuild && !depsOptimizer) || externalize) {
// Resolve package side effects for build so that rollup can better
// perform tree-shaking
return processResult({
id: resolved,
moduleSideEffects: pkg.hasSideEffects(resolved),
})
}
const ext = path.extname(resolved)
const isCJS =
ext === '.cjs' || (ext === '.js' && nearestPkg.data.type !== 'module')
if (
!options.ssrOptimizeCheck &&
(!resolved.includes('node_modules') || // linked
!depsOptimizer || // resolving before listening to the server
options.scan) // initial esbuild scan phase
) {
return { id: resolved }
}
// if we reach here, it's a valid dep import that hasn't been optimized.
const isJsType = depsOptimizer
? isOptimizable(resolved, depsOptimizer.options)
: OPTIMIZABLE_ENTRY_RE.test(resolved)
let exclude = depsOptimizer?.options.exclude
let include = depsOptimizer?.options.include
if (options.ssrOptimizeCheck) {
// we don't have the depsOptimizer
exclude = options.ssrConfig?.optimizeDeps?.exclude
include = options.ssrConfig?.optimizeDeps?.include
}
const skipOptimization =
!isJsType ||
importer?.includes('node_modules') ||
exclude?.includes(pkgId) ||
exclude?.includes(id) ||
SPECIAL_QUERY_RE.test(resolved) ||
// During dev SSR, we don't have a way to reload the module graph if
// a non-optimized dep is found. So we need to skip optimization here.
// The only optimized deps are the ones explicitly listed in the config.
(!options.ssrOptimizeCheck && !isBuild && ssr) ||
// Only optimize non-external CJS deps during SSR by default
(ssr && !isCJS && !(include?.includes(pkgId) || include?.includes(id)))
if (options.ssrOptimizeCheck) {
return {
id: skipOptimization
? injectQuery(resolved, `__vite_skip_optimization`)
: resolved,
}
}
if (skipOptimization) {
// excluded from optimization
// Inject a version query to npm deps so that the browser
// can cache it without re-validation, but only do so for known js types.
// otherwise we may introduce duplicated modules for externalized files
// from pre-bundled deps.
if (!isBuild) {
const versionHash = depsOptimizer!.metadata.browserHash
if (versionHash && isJsType) {
resolved = injectQuery(resolved, `v=${versionHash}`)
}
}
} else {
// this is a missing import, queue optimize-deps re-run and
// get a resolved its optimized info
const optimizedInfo = depsOptimizer!.registerMissingImport(id, resolved)
resolved = depsOptimizer!.getOptimizedDepId(optimizedInfo)
}
if (isBuild) {
// Resolve package side effects for build so that rollup can better
// perform tree-shaking
return {
id: resolved,
moduleSideEffects: pkg.hasSideEffects(resolved),
}
} else {
return { id: resolved! }
}
}
export async function tryOptimizedResolve(
depsOptimizer: DepsOptimizer,
id: string,
importer?: string,
): Promise<string | undefined> {
// TODO: we need to wait until scanning is done here as this function
// is used in the preAliasPlugin to decide if an aliased dep is optimized,
// and avoid replacing the bare import with the resolved path.
// We should be able to remove this in the future
await depsOptimizer.scanProcessing
const metadata = depsOptimizer.metadata
const depInfo = optimizedDepInfoFromId(metadata, id)
if (depInfo) {
return depsOptimizer.getOptimizedDepId(depInfo)
}
if (!importer) return
// further check if id is imported by nested dependency
let resolvedSrc: string | undefined
for (const optimizedData of metadata.depInfoList) {
if (!optimizedData.src) continue // Ignore chunks
const pkgPath = optimizedData.id
// check for scenarios, e.g.
// pkgPath => "my-lib > foo"
// id => "foo"
// this narrows the need to do a full resolve
if (!pkgPath.endsWith(id)) continue
// lazily initialize resolvedSrc
if (resolvedSrc == null) {
try {
// this may throw errors if unable to resolve, e.g. aliased id
resolvedSrc = normalizePath(resolveFrom(id, path.dirname(importer)))
} catch {
// this is best-effort only so swallow errors
break
}
}
// match by src to correctly identify if id belongs to nested dependency
if (optimizedData.src === resolvedSrc) {
return depsOptimizer.getOptimizedDepId(optimizedData)
}
}
}
export function resolvePackageEntry(
id: string,
{ dir, data, setResolvedCache, getResolvedCache }: PackageData,
targetWeb: boolean,
options: InternalResolveOptions,
): string | undefined {
const cached = getResolvedCache('.', targetWeb)
if (cached) {
return cached
}
try {
let entryPoint: string | undefined
// resolve exports field with highest priority
// using https://github.com/lukeed/resolve.exports
if (data.exports) {
entryPoint = resolveExportsOrImports(
data,
'.',
options,
targetWeb,
'exports',
)
}
const resolvedFromExports = !!entryPoint
// if exports resolved to .mjs, still resolve other fields.
// This is because .mjs files can technically import .cjs files which would
// make them invalid for pure ESM environments - so if other module/browser
// fields are present, prioritize those instead.
if (
targetWeb &&
options.browserField &&
(!entryPoint || entryPoint.endsWith('.mjs'))
) {
// check browser field
// https://github.com/defunctzombie/package-browser-field-spec
const browserEntry =