Skip to content

Commit 1ea38e2

Browse files
authoredApr 5, 2023
refactor: use resolvePackageData in requireResolveFromRootWithFallback (#12712)
1 parent 8e30025 commit 1ea38e2

File tree

1 file changed

+14
-9
lines changed

1 file changed

+14
-9
lines changed
 

‎packages/vite/src/node/utils.ts

+14-9
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import os from 'node:os'
33
import path from 'node:path'
44
import { exec } from 'node:child_process'
55
import { createHash } from 'node:crypto'
6-
import { URL, URLSearchParams } from 'node:url'
6+
import { URL, URLSearchParams, fileURLToPath } from 'node:url'
77
import { builtinModules, createRequire } from 'node:module'
88
import { promises as dns } from 'node:dns'
99
import { performance } from 'node:perf_hooks'
@@ -34,6 +34,7 @@ import {
3434
import type { DepOptimizationConfig } from './optimizer'
3535
import type { ResolvedConfig } from './config'
3636
import type { ResolvedServerUrls, ViteDevServer } from './server'
37+
import { resolvePackageData } from './packages'
3738
import type { CommonServerOptions } from '.'
3839

3940
/**
@@ -966,21 +967,25 @@ export function getHash(text: Buffer | string): string {
966967
return createHash('sha256').update(text).digest('hex').substring(0, 8)
967968
}
968969

970+
const _dirname = path.dirname(fileURLToPath(import.meta.url))
971+
969972
export const requireResolveFromRootWithFallback = (
970973
root: string,
971974
id: string,
972975
): string => {
973-
const paths = _require.resolve.paths?.(id) || []
974-
// Search in the root directory first, and fallback to the default require paths.
975-
paths.unshift(root)
976-
977-
// Use `resolve` package to check existence first, so if the package is not found,
976+
// check existence first, so if the package is not found,
978977
// it won't be cached by nodejs, since there isn't a way to invalidate them:
979978
// https://github.com/nodejs/node/issues/44663
980-
resolve.sync(id, { basedir: root, paths })
979+
const found = resolvePackageData(id, root) || resolvePackageData(id, _dirname)
980+
if (!found) {
981+
const error = new Error(`${JSON.stringify(id)} not found.`)
982+
;(error as any).code = 'MODULE_NOT_FOUND'
983+
throw error
984+
}
981985

982-
// Use `require.resolve` again as the `resolve` package doesn't support the `exports` field
983-
return _require.resolve(id, { paths })
986+
// actually resolve
987+
// Search in the root directory first, and fallback to the default require paths.
988+
return _require.resolve(id, { paths: [root, _dirname] })
984989
}
985990

986991
export function emptyCssComments(raw: string): string {

0 commit comments

Comments
 (0)
Please sign in to comment.