Created
March 2, 2020 02:30
-
-
Save gcangussu/3aeaa693f2df28d74ea85b59fdc305e3 to your computer and use it in GitHub Desktop.
Prevent Node.js require looking for node_modules in parent directories. Usefull for isolating your project against node_modules directories upward in the file hierarchy.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Put this on the top of your entry file or use Node's `-r` cli option | |
const { Module } = require("module"); | |
const originalResolveLookupPaths = Module._resolveLookupPaths; | |
Module._resolveLookupPaths = function(request, parent) { | |
const paths = originalResolveLookupPaths.call(Module, request, parent); | |
if (request.startsWith(".")) return paths; | |
// Remove all modules directories upward in the hierarchy from this | |
// file's directory (non inclusive). | |
const lastSearchPathIndex = paths.indexOf(`${__dirname}/node_modules`); | |
return lastSearchPathIndex !== -1 | |
? paths.slice(0, lastSearchPathIndex + 1) | |
: paths; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment