1
+ const Module = require ( 'module' )
2
+ const path = require ( 'path' )
3
+
1
4
const semver = require ( 'semver' )
2
5
6
+ // https://github.com/benmosher/eslint-plugin-import/pull/1591
7
+ // https://github.com/benmosher/eslint-plugin-import/pull/1602
8
+ // Polyfill Node's `Module.createRequireFromPath` if not present (added in Node v10.12.0)
9
+ // Use `Module.createRequire` if available (added in Node v12.2.0)
10
+ const createRequire = Module . createRequire || Module . createRequireFromPath || function ( filename ) {
11
+ const mod = new Module ( filename , null )
12
+ mod . filename = filename
13
+ mod . paths = Module . _nodeModulePaths ( path . dirname ( filename ) )
14
+
15
+ mod . _compile ( `module.exports = require;` , filename )
16
+
17
+ return mod . exports
18
+ }
19
+
3
20
function resolveFallback ( request , options ) {
4
- const Module = require ( 'module' )
5
21
const isMain = false
6
22
const fakeParent = new Module ( '' , null )
7
23
8
24
const paths = [ ]
9
25
10
26
for ( let i = 0 ; i < options . paths . length ; i ++ ) {
11
- const path = options . paths [ i ]
12
- fakeParent . paths = Module . _nodeModulePaths ( path )
27
+ const p = options . paths [ i ]
28
+ fakeParent . paths = Module . _nodeModulePaths ( p )
13
29
const lookupPaths = Module . _resolveLookupPaths ( request , fakeParent , true )
14
30
15
- if ( ! paths . includes ( path ) ) paths . push ( path )
31
+ if ( ! paths . includes ( p ) ) paths . push ( p )
16
32
17
33
for ( let j = 0 ; j < lookupPaths . length ; j ++ ) {
18
34
if ( ! paths . includes ( lookupPaths [ j ] ) ) paths . push ( lookupPaths [ j ] )
@@ -35,20 +51,26 @@ const resolve = semver.satisfies(process.version, '>=10.0.0')
35
51
exports . resolveModule = function ( request , context ) {
36
52
let resolvedPath
37
53
try {
38
- resolvedPath = resolve ( request , {
39
- paths : [ context ]
40
- } )
54
+ try {
55
+ resolvedPath = createRequire ( path . resolve ( context , 'package.json' ) ) . resolve ( request )
56
+ } catch ( e ) {
57
+ resolvedPath = resolve ( request , { paths : [ context ] } )
58
+ }
41
59
} catch ( e ) { }
42
60
return resolvedPath
43
61
}
44
62
45
63
exports . loadModule = function ( request , context , force = false ) {
46
- const resolvedPath = exports . resolveModule ( request , context )
47
- if ( resolvedPath ) {
48
- if ( force ) {
49
- clearRequireCache ( resolvedPath )
64
+ try {
65
+ return createRequire ( path . resolve ( context , 'package.json' ) ) ( request )
66
+ } catch ( e ) {
67
+ const resolvedPath = exports . resolveModule ( request , context )
68
+ if ( resolvedPath ) {
69
+ if ( force ) {
70
+ clearRequireCache ( resolvedPath )
71
+ }
72
+ return require ( resolvedPath )
50
73
}
51
- return require ( resolvedPath )
52
74
}
53
75
}
54
76
0 commit comments