Skip to content

Commit

Permalink
Make module-alias work in cli mode (#76)
Browse files Browse the repository at this point in the history
Make module-alias work in cli mode
  • Loading branch information
ilearnio authored Oct 1, 2019
2 parents 07a6b80 + b377450 commit 652604b
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
19 changes: 15 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,15 @@ function addPath (path) {
if (modulePaths.indexOf(path) === -1) {
modulePaths.push(path)
// Enable the search path for the current top-level module
addPathHelper(path, require.main.paths)
var mainModule = getMainModule()
if (mainModule) {
addPathHelper(path, mainModule.paths)
}
parent = module.parent

// Also modify the paths of the module that was used to load the
// app-module-paths module and all of it's parents
while (parent && parent !== require.main) {
while (parent && parent !== mainModule) {
addPathHelper(path, parent.paths)
parent = parent.parent
}
Expand All @@ -113,9 +116,13 @@ function addAlias (alias, target) {
* The function is undocumented and for testing purposes only
*/
function reset () {
var mainModule = getMainModule()

// Reset all changes in paths caused by addPath function
modulePaths.forEach(function (path) {
removePathHelper(path, require.main.paths)
if (mainModule) {
removePathHelper(path, mainModule.paths)
}

// Delete from require.cache if the module has been required before.
// This is required for node >= 11
Expand All @@ -126,7 +133,7 @@ function reset () {
})

var parent = module.parent
while (parent && parent !== require.main) {
while (parent && parent !== mainModule) {
removePathHelper(path, parent.paths)
parent = parent.parent
}
Expand Down Expand Up @@ -205,6 +212,10 @@ function init (options) {
}
}

function getMainModule () {
return require.main._simulateRepl ? undefined : require.main
}

module.exports = init
module.exports.addPath = addPath
module.exports.addAlias = addAlias
Expand Down
18 changes: 18 additions & 0 deletions test/specs.js
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,24 @@ describe('module-alias', function () {
})
})

context('when used from the REPL', function () {
before(function () {
require.main._simulateRepl = true
})

after(function () {
delete require.main._simulateRepl
})

it('should addPath', function () {
moduleAlias.addPath('some-path')
})

it('should reset', function () {
moduleAlias.reset()
})
})

it('should support forked modules', function () {
expect(typeof require('hello-world-classic')).to.equal('function')
})
Expand Down

0 comments on commit 652604b

Please sign in to comment.