diff --git a/index.js b/index.js index 7551a0f..8f2e570 100644 --- a/index.js +++ b/index.js @@ -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 } @@ -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 @@ -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 } @@ -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 diff --git a/test/specs.js b/test/specs.js index 0582e79..4793827 100644 --- a/test/specs.js +++ b/test/specs.js @@ -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') })