@@ -82,12 +82,15 @@ function addPath (path) {
8282 if ( modulePaths . indexOf ( path ) === - 1 ) {
8383 modulePaths . push ( path )
8484 // Enable the search path for the current top-level module
85- addPathHelper ( path , require . main . paths )
85+ var mainModule = getMainModule ( )
86+ if ( mainModule ) {
87+ addPathHelper ( path , mainModule . paths )
88+ }
8689 parent = module . parent
8790
8891 // Also modify the paths of the module that was used to load the
8992 // app-module-paths module and all of it's parents
90- while ( parent && parent !== require . main ) {
93+ while ( parent && parent !== mainModule ) {
9194 addPathHelper ( path , parent . paths )
9295 parent = parent . parent
9396 }
@@ -113,9 +116,13 @@ function addAlias (alias, target) {
113116 * The function is undocumented and for testing purposes only
114117 */
115118function reset ( ) {
119+ var mainModule = getMainModule ( )
120+
116121 // Reset all changes in paths caused by addPath function
117122 modulePaths . forEach ( function ( path ) {
118- removePathHelper ( path , require . main . paths )
123+ if ( mainModule ) {
124+ removePathHelper ( path , mainModule . paths )
125+ }
119126
120127 // Delete from require.cache if the module has been required before.
121128 // This is required for node >= 11
@@ -126,7 +133,7 @@ function reset () {
126133 } )
127134
128135 var parent = module . parent
129- while ( parent && parent !== require . main ) {
136+ while ( parent && parent !== mainModule ) {
130137 removePathHelper ( path , parent . paths )
131138 parent = parent . parent
132139 }
@@ -205,6 +212,10 @@ function init (options) {
205212 }
206213}
207214
215+ function getMainModule ( ) {
216+ return require . main . _simulateRepl ? undefined : require . main
217+ }
218+
208219module . exports = init
209220module . exports . addPath = addPath
210221module . exports . addAlias = addAlias
0 commit comments