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 fileSystem = new CachedInputFileSystem ( fs , 30_000 )
7
+
8
+ const esmResolver = ResolverFactory . createResolver ( {
9
+ fileSystem,
10
+ useSyncFileSystemCalls : true ,
11
+ extensions : [ '.mjs' , '.js' ] ,
12
+ mainFields : [ 'module' ] ,
13
+ conditionNames : [ 'node' , 'import' ] ,
14
+ } )
15
+
16
+ const cjsResolver = ResolverFactory . createResolver ( {
17
+ fileSystem,
18
+ useSyncFileSystemCalls : true ,
19
+ extensions : [ '.js' , '.cjs' ] ,
20
+ mainFields : [ 'main' ] ,
21
+ conditionNames : [ 'node' , 'require' ] ,
22
+ } )
6
23
7
24
// This is a long-lived cache for resolved modules whether they exist or not
8
25
// Because we're compatible with a large number of plugins, we need to check
@@ -11,17 +28,11 @@ const localRequire = req(import.meta.url)
11
28
// failed module resolutions making repeated checks very expensive.
12
29
const resolveCache = expiringMap < string , string | null > ( 30_000 )
13
30
14
- export function resolveIn ( id : string , paths : string [ ] ) {
15
- return localRequire . resolve ( id , {
16
- paths,
17
- } )
18
- }
19
-
20
31
export function maybeResolve ( name : string ) {
21
32
let modpath = resolveCache . get ( name )
22
33
23
34
if ( modpath === undefined ) {
24
- modpath = freshMaybeResolve ( name )
35
+ modpath = resolveJsFrom ( fileURLToPath ( import . meta . url ) , name )
25
36
resolveCache . set ( name , modpath )
26
37
}
27
38
@@ -39,12 +50,10 @@ export async function loadIfExists<T>(name: string): Promise<T | null> {
39
50
return null
40
51
}
41
52
42
- function freshMaybeResolve ( name : string ) {
53
+ export function resolveJsFrom ( base : string , id : string ) : string {
43
54
try {
44
- return localRequire . resolve ( name )
55
+ return esmResolver . resolveSync ( { } , base , id ) || id
45
56
} catch ( err ) {
46
- return null
57
+ return cjsResolver . resolveSync ( { } , base , id ) || id
47
58
}
48
59
}
49
-
50
- export { resolveFrom }
0 commit comments