Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make module-alias work in cli mode #76

Merged
merged 2 commits into from
Oct 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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