1+ const Module = require ( 'module' )
2+ const path = require ( 'path' )
3+
14const semver = require ( 'semver' )
25
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+
320function resolveFallback ( request , options ) {
4- const Module = require ( 'module' )
521 const isMain = false
622 const fakeParent = new Module ( '' , null )
723
824 const paths = [ ]
925
1026 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 )
1329 const lookupPaths = Module . _resolveLookupPaths ( request , fakeParent , true )
1430
15- if ( ! paths . includes ( path ) ) paths . push ( path )
31+ if ( ! paths . includes ( p ) ) paths . push ( p )
1632
1733 for ( let j = 0 ; j < lookupPaths . length ; j ++ ) {
1834 if ( ! paths . includes ( lookupPaths [ j ] ) ) paths . push ( lookupPaths [ j ] )
@@ -35,20 +51,26 @@ const resolve = semver.satisfies(process.version, '>=10.0.0')
3551exports . resolveModule = function ( request , context ) {
3652 let resolvedPath
3753 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+ }
4159 } catch ( e ) { }
4260 return resolvedPath
4361}
4462
4563exports . 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 )
5073 }
51- return require ( resolvedPath )
5274 }
5375}
5476
0 commit comments