Skip to content

Commit 652604b

Browse files
authored
Make module-alias work in cli mode (#76)
Make module-alias work in cli mode
2 parents 07a6b80 + b377450 commit 652604b

File tree

2 files changed

+33
-4
lines changed

2 files changed

+33
-4
lines changed

index.js

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -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
*/
115118
function 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+
208219
module.exports = init
209220
module.exports.addPath = addPath
210221
module.exports.addAlias = addAlias

test/specs.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,24 @@ describe('module-alias', function () {
158158
})
159159
})
160160

161+
context('when used from the REPL', function () {
162+
before(function () {
163+
require.main._simulateRepl = true
164+
})
165+
166+
after(function () {
167+
delete require.main._simulateRepl
168+
})
169+
170+
it('should addPath', function () {
171+
moduleAlias.addPath('some-path')
172+
})
173+
174+
it('should reset', function () {
175+
moduleAlias.reset()
176+
})
177+
})
178+
161179
it('should support forked modules', function () {
162180
expect(typeof require('hello-world-classic')).to.equal('function')
163181
})

0 commit comments

Comments
 (0)