-
-
Notifications
You must be signed in to change notification settings - Fork 6.4k
/
Copy pathresolve.ts
524 lines (474 loc) · 14 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
import fs from 'fs'
import path from 'path'
import { Plugin } from '../plugin'
import chalk from 'chalk'
import { FS_PREFIX, SUPPORTED_EXTS } from '../constants'
import {
bareImportRE,
createDebugger,
deepImportRE,
injectQuery,
isDataUrl,
isExternalUrl,
isObject,
normalizePath,
fsPathFromId,
resolveFrom
} from '../utils'
import { ResolvedConfig, ViteDevServer } from '..'
import slash from 'slash'
import { createFilter } from '@rollup/pluginutils'
import { PartialResolvedId } from 'rollup'
import isBuiltin from 'isbuiltin'
import { isCSSRequest } from './css'
const mainFields = ['module', 'jsnext', 'jsnext:main', 'main']
// special id for paths marked with browser: false
// https://github.com/defunctzombie/package-browser-field-spec#ignore-a-module
const browserExternalId = '__browser-external'
const isDebug = process.env.DEBUG
const debug = createDebugger('vite:resolve-details', {
onlyWhenFocused: true
})
interface ResolveOptions {
root: string
isBuild: boolean
/**
* src code mode also attempts the following:
* - resolving /xxx as URLs
* - resolving bare imports from optimized deps
*/
asSrc: boolean
dedupe?: string[]
}
export function resolvePlugin({
root,
isBuild,
asSrc,
dedupe
}: ResolveOptions): Plugin {
let config: ResolvedConfig | undefined
let server: ViteDevServer | undefined
return {
name: 'vite:resolve',
configureServer(_server) {
server = _server
},
configResolved(_config) {
config = _config
},
resolveId(id, importer) {
if (id === browserExternalId) {
return id
}
// fast path for commonjs proxy modules
if (/\?commonjs/.test(id) || id === 'commonjsHelpers.js') {
return
}
let res
// explicit fs paths that starts with /@fs/*
if (asSrc && id.startsWith(FS_PREFIX)) {
const fsPath = fsPathFromId(id)
res = tryFsResolve(fsPath, false)
isDebug && debug(`[@fs] ${chalk.cyan(id)} -> ${chalk.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 res || fsPath
}
// URL
// /foo -> /fs-root/foo
if (asSrc && id.startsWith('/')) {
const fsPath = path.resolve(root, id.slice(1))
if ((res = tryFsResolve(fsPath))) {
isDebug && debug(`[url] ${chalk.cyan(id)} -> ${chalk.dim(res)}`)
return res
}
}
// relative
if (id.startsWith('.')) {
const basedir = importer ? path.dirname(importer) : process.cwd()
let fsPath = path.resolve(basedir, id)
// handle browser field mapping for relative imports
const pkg = importer && idToPkgMap.get(importer)
if (pkg && isObject(pkg.data.browser)) {
const pkgRealtivePath = './' + slash(path.relative(pkg.dir, fsPath))
const browserMappedPath = mapWithBrowserField(
pkgRealtivePath,
pkg.data.browser
)
if (browserMappedPath) {
fsPath = path.resolve(pkg.dir, browserMappedPath)
} else {
return browserExternalId
}
}
if ((res = tryFsResolve(fsPath))) {
isDebug && debug(`[relative] ${chalk.cyan(id)} -> ${chalk.dim(res)}`)
if (pkg) {
idToPkgMap.set(res, pkg)
}
return res
}
}
// absolute fs paths
if (path.isAbsolute(id) && (res = tryFsResolve(id))) {
isDebug && debug(`[fs] ${chalk.cyan(id)} -> ${chalk.dim(res)}`)
return res
}
// external
if (isExternalUrl(id) || isDataUrl(id)) {
return {
id,
external: true
}
}
// bare package imports, perform node resolve
if (bareImportRE.test(id)) {
// externalize node built-ins only when building for ssr
if (isBuild && config && config.build.ssr && isBuiltin(id)) {
return {
id,
external: true
}
}
if (asSrc && server && (res = tryOptimizedResolve(id, server))) {
return res
}
if (
(res = tryNodeResolve(
id,
importer ? path.dirname(importer) : root,
isBuild,
dedupe,
root,
server
))
) {
return res
}
}
isDebug && debug(`[fallthrough] ${chalk.dim(id)}`)
},
load(id) {
if (id === browserExternalId) {
return `export default {}`
}
}
}
}
function tryFsResolve(fsPath: string, tryIndex = true): string | undefined {
const [file, q] = fsPath.split(`?`, 2)
const query = q ? `?${q}` : ``
let res: string | undefined
if ((res = tryResolveFile(file, query, tryIndex))) {
return res
}
for (const ext of SUPPORTED_EXTS) {
if ((res = tryResolveFile(file + ext, query, tryIndex))) {
return res
}
}
}
function tryResolveFile(
file: string,
query: string,
tryIndex: boolean
): string | undefined {
if (fs.existsSync(file)) {
const isDir = fs.statSync(file).isDirectory()
if (isDir) {
if (tryIndex) {
const index = tryFsResolve(file + '/index', false)
if (index) return normalizePath(index) + query
}
const pkgPath = file + '/package.json'
if (fs.existsSync(pkgPath)) {
// path points to a node package
const pkg = loadPackageData(pkgPath)
return resolvePackageEntry(file, pkg)
}
} else {
return normalizePath(file) + query
}
}
}
const idToPkgMap = new Map<string, PackageData>()
export function tryNodeResolve(
id: string,
basedir: string,
isBuild = true,
dedupe?: string[],
dedupeRoot?: string,
server?: ViteDevServer
): PartialResolvedId | undefined {
const deepMatch = id.match(deepImportRE)
const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : id
if (dedupe && dedupeRoot && dedupe.includes(pkgId)) {
basedir = dedupeRoot
}
const pkg = resolvePackageData(pkgId, basedir)
if (!pkg) {
return
}
// prevent deep imports to optimized deps.
if (
deepMatch &&
server &&
server.optimizeDepsMetadata &&
pkg.data.name in server.optimizeDepsMetadata.map &&
!isCSSRequest(id)
) {
throw new Error(
chalk.yellow(
`Deep import "${chalk.cyan(
id
)}" should be avoided because dependency "${chalk.cyan(
pkg.data.name
)}" has been pre-optimized. Prefer importing directly from the module entry:\n\n` +
`${chalk.green(`import { ... } from "${pkg.data.name}"`)}\n\n` +
`If the used import is not exported from the package's main entry ` +
`and can only be attained via deep import, you can explicitly add ` +
`the deep import path to "optimizeDeps.include" in vite.config.js.`
)
)
}
let resolved = deepMatch
? resolveDeepImport(id, pkg)
: resolvePackageEntry(id, pkg)
if (!resolved) {
return
}
// link id to pkg for browser field mapping check
idToPkgMap.set(resolved, pkg)
if (isBuild) {
// Resolve package side effects for build so that rollup can better
// perform tree-shaking
return {
id: resolved,
moduleSideEffects: pkg.hasSideEffects(resolved)
}
} else {
// During serve, inject a version query to npm deps so that the browser
// can cache it without revalidation. Make sure to apply this only to
// files actually inside node_modules so that locally linked packages
// in monorepos are not cached this way.
if (resolved.includes('node_modules')) {
const versionHash = server?.optimizeDepsMetadata?.hash
if (versionHash) {
resolved = injectQuery(resolved, `v=${versionHash}`)
}
}
return { id: resolved }
}
}
function tryOptimizedResolve(
rawId: string,
server: ViteDevServer
): string | undefined {
const cacheDir = server.config.optimizeCacheDir
const depData = server.optimizeDepsMetadata
if (cacheDir && depData) {
const [id, q] = rawId.split(`?`, 2)
const query = q ? `?${q}` : ``
const filePath = depData.map[id]
if (filePath) {
return normalizePath(path.resolve(cacheDir, filePath)) + query
}
}
}
export interface PackageData {
dir: string
hasSideEffects: (id: string) => boolean
data: {
[field: string]: any
version: string
main: string
module: string
browser: string | Record<string, string | false>
exports: string | Record<string, any> | string[]
dependencies: Record<string, string>
}
}
const packageCache = new Map<string, PackageData>()
export function resolvePackageData(
id: string,
basedir: string
): PackageData | undefined {
const cacheKey = id + basedir
if (packageCache.has(cacheKey)) {
return packageCache.get(cacheKey)
}
try {
const pkgPath = resolveFrom(`${id}/package.json`, basedir)
return loadPackageData(pkgPath, cacheKey)
} catch (e) {
isDebug && debug(`${chalk.red(`[failed loading package.json]`)} ${id}`)
}
}
function loadPackageData(pkgPath: string, cacheKey = pkgPath) {
const data = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))
const pkgDir = path.dirname(pkgPath)
const { sideEffects } = data
let hasSideEffects
if (typeof sideEffects === 'boolean') {
hasSideEffects = () => sideEffects
} else if (Array.isArray(sideEffects)) {
hasSideEffects = createFilter(sideEffects, null, { resolve: pkgDir })
} else {
hasSideEffects = () => true
}
const pkg = {
dir: pkgDir,
data,
hasSideEffects
}
packageCache.set(cacheKey, pkg)
return pkg
}
export function resolvePackageEntry(
id: string,
{ dir, data }: PackageData
): string | undefined {
let entryPoint: string | undefined
// check browser field first with highest priority
const browserEntry =
typeof data.browser === 'string'
? data.browser
: isObject(data.browser) && data.browser['.']
if (browserEntry) {
entryPoint = browserEntry
}
if (!entryPoint) {
// resolve exports field
// https://nodejs.org/api/packages.html#packages_package_entry_points
const { exports: exportsField } = data
if (exportsField) {
if (typeof exportsField === 'string') {
entryPoint = exportsField
} else if (Array.isArray(exportsField)) {
entryPoint = exportsField[0]
} else if (isObject(exportsField)) {
if ('.' in exportsField) {
entryPoint = resolveConditionalExports(exportsField['.'])
} else {
entryPoint = resolveConditionalExports(exportsField)
}
}
}
}
if (!entryPoint) {
for (const field of mainFields) {
if (typeof data[field] === 'string') {
entryPoint = data[field]
break
}
}
}
entryPoint = entryPoint || 'index.js'
// resolve object browser field in package.json
// https://github.com/defunctzombie/package-browser-field-spec
const { browser: browserField } = data
if (isObject(browserField)) {
entryPoint = mapWithBrowserField(entryPoint, browserField) || entryPoint
}
entryPoint = path.resolve(dir, entryPoint)
const resolvedEntryPont = tryFsResolve(entryPoint)
if (resolvedEntryPont) {
isDebug &&
debug(
`[package entry] ${chalk.cyan(id)} -> ${chalk.dim(resolvedEntryPont)}`
)
return resolvedEntryPont
} else {
throw new Error(
`Failed to resolve entry for package "${id}". ` +
`The package may have incorrect main/module/exports specified in its package.json.`
)
}
}
function resolveDeepImport(
id: string,
{ dir, data }: PackageData
): string | undefined {
let relativeId: string | undefined = '.' + id.slice(data.name.length)
const { exports: exportsField, browser: browserField } = data
// map relative based on exports data
if (exportsField) {
let isExported = false
if (isObject(exportsField) && !Array.isArray(exportsField)) {
if (relativeId in exportsField) {
relativeId = resolveConditionalExports(exportsField[relativeId])
isExported = true
} else {
for (const key in exportsField) {
if (key.endsWith('/') && relativeId.startsWith(key)) {
// directory mapping
const replacement = resolveConditionalExports(exportsField[key])
relativeId = replacement && relativeId.replace(key, replacement)
isExported = true
break
}
}
}
}
if (!isExported || !relativeId) {
throw new Error(
`Package subpath '${relativeId}' is not defined by "exports" in ` +
`${path.join(dir, 'package.json')}.`
)
}
} else if (isObject(browserField)) {
const mapped = mapWithBrowserField(relativeId, browserField)
if (mapped) {
relativeId = mapped
} else {
return browserExternalId
}
}
if (relativeId) {
const resolved = tryFsResolve(path.resolve(dir, relativeId), !exportsField)
if (resolved) {
isDebug &&
debug(`[node/deep-import] ${chalk.cyan(id)} -> ${chalk.dim(resolved)}`)
return resolved
}
}
}
function resolveConditionalExports(exp: any): string | undefined {
if (typeof exp === 'string') {
return exp
} else if (isObject(exp)) {
if (typeof exp.browser === 'string') {
return exp.browser
} else if (typeof exp.import === 'string') {
return exp.import
} else if (typeof exp.default === 'string') {
return exp.default
}
} else if (Array.isArray(exp)) {
for (let i = 0; i < exp.length; i++) {
const res = resolveConditionalExports(exp[i])
if (res) return res
}
}
}
/**
* given a relative path in pkg dir,
* return a relative path in pkg dir,
* mapped with the "map" object
*/
function mapWithBrowserField(
relativePathInPkgDir: string,
map: Record<string, string | false>
) {
const normalized = normalize(relativePathInPkgDir)
const foundEntry = Object.entries(map).find(
([from]) => normalize(from) === normalized
)
if (!foundEntry) {
return relativePathInPkgDir
}
return foundEntry[1]
}
function normalize(file: string) {
return path.posix.normalize(path.extname(file) ? file : file + '.js')
}