@@ -18,12 +18,75 @@ module.exports = function requireHook (opts) {
1818 var hasSetMain = false ;
1919 var currentWrapFile = null ;
2020
21+ function resolveSymlink ( filePath ) {
22+ while ( fs . existsSync ( filePath ) && fs . lstatSync ( filePath ) . isSymbolicLink ( ) ) {
23+ filePath = fs . readlinkSync ( filePath ) ;
24+ }
25+ return filePath ;
26+ }
27+
28+ // Searches each parent directory for a 'package.json'
29+ function resolvePackage ( pkgRoot ) {
30+ while ( pkgRoot !== path . sep ) {
31+ pkgPath = path . join ( pkgRoot , 'package.json' ) ;
32+ if ( fs . existsSync ( pkgPath ) ) {
33+ return resolveSymlink ( pkgRoot ) ;
34+ }
35+ pkgRoot = path . dirname ( pkgRoot ) ;
36+ }
37+ return null ;
38+ }
39+
40+ // Searches each 'node_modules' directory
41+ // for a module (including the global root)
42+ function resolveModule ( request , parent ) {
43+ var pkgRoot = resolvePackage (
44+ parent . id === '.' ?
45+ process . cwd ( ) :
46+ path . dirname ( parent . id )
47+ ) ;
48+ if ( pkgRoot ) {
49+ var depName = request . split ( path . sep ) [ 0 ] ;
50+ var depPath = resolveSymlink (
51+ path . join ( pkgRoot , 'node_modules' , depName )
52+ ) ;
53+ if ( fs . existsSync ( depPath ) ) {
54+ return path . join (
55+ depPath ,
56+ path . relative ( depName , request )
57+ ) ;
58+ }
59+
60+ //
61+ // Search each directory in $NODE_PATH
62+ //
63+ var nodePaths = process . env . NODE_PATH . split ( ':' ) ;
64+ for ( var i = 0 ; i < nodePaths . length ; i ++ ) {
65+ pkgRoot = nodePaths [ i ] ;
66+ if ( fs . existsSync ( pkgRoot ) && fs . statSync ( pkgRoot ) . isDirectory ( ) ) {
67+ depPath = resolveSymlink (
68+ path . join ( pkgRoot , depName )
69+ ) ;
70+ if ( fs . existsSync ( depPath ) ) {
71+ return path . join (
72+ depPath ,
73+ path . relative ( depName , request )
74+ ) ;
75+ }
76+ }
77+ }
78+ }
79+ return request ;
80+ }
81+
2182 var loadModule = Module . _load ;
2283 Module . _load = function ( request , parent , isMain ) {
2384 if ( request [ 0 ] === '.' ) {
2485 if ( parent . id === '.' ) {
2586 request = path . resolve ( process . cwd ( ) , request ) ;
2687 }
88+ } else if ( request [ 0 ] !== path . sep ) {
89+ request = resolveModule ( request , parent ) ;
2790 }
2891 return loadModule ( request , parent , isMain ) ;
2992 } ;
0 commit comments