1
- import { createRequire as req } from 'node:module'
2
- import resolveFrom from 'resolve-from'
1
+ import fs from 'node:fs'
2
+ import { fileURLToPath } from 'node:url'
3
+ import { CachedInputFileSystem , ResolverFactory } from 'enhanced-resolve'
3
4
import { expiringMap } from './expiring-map'
4
5
5
- const localRequire = req ( import . meta. url )
6
+ const esmResolver = ResolverFactory . createResolver ( {
7
+ fileSystem : new CachedInputFileSystem ( fs , 30_000 ) ,
8
+ useSyncFileSystemCalls : true ,
9
+ extensions : [ '.mjs' , '.js' , '.cjs' ] ,
10
+ mainFields : [ 'module' , 'main' ] ,
11
+ conditionNames : [ 'node' , 'import' , 'require' ] ,
12
+ } )
6
13
7
14
// This is a long-lived cache for resolved modules whether they exist or not
8
15
// Because we're compatible with a large number of plugins, we need to check
@@ -11,17 +18,11 @@ const localRequire = req(import.meta.url)
11
18
// failed module resolutions making repeated checks very expensive.
12
19
const resolveCache = expiringMap < string , string | null > ( 30_000 )
13
20
14
- export function resolveIn ( id : string , paths : string [ ] ) {
15
- return localRequire . resolve ( id , {
16
- paths,
17
- } )
18
- }
19
-
20
21
export function maybeResolve ( name : string ) {
21
22
let modpath = resolveCache . get ( name )
22
23
23
24
if ( modpath === undefined ) {
24
- modpath = freshMaybeResolve ( name )
25
+ modpath = resolveJsFrom ( fileURLToPath ( import . meta . url ) , name )
25
26
resolveCache . set ( name , modpath )
26
27
}
27
28
@@ -39,12 +40,11 @@ export async function loadIfExists<T>(name: string): Promise<T | null> {
39
40
return null
40
41
}
41
42
42
- function freshMaybeResolve ( name : string ) {
43
- try {
44
- return localRequire . resolve ( name )
45
- } catch ( err ) {
46
- return null
47
- }
48
- }
43
+ export function resolveJsFrom ( base : string , id : string ) : string {
44
+ let result = esmResolver . resolveSync ( { } , base , id )
45
+ if ( result ) return result
49
46
50
- export { resolveFrom }
47
+ throw new Error (
48
+ `Cannot find module "${ id } " (searching relative to: "${ base } ")` ,
49
+ )
50
+ }
0 commit comments