Skip to content

Instantly share code, notes, and snippets.

@gcangussu
Created March 2, 2020 02:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gcangussu/3aeaa693f2df28d74ea85b59fdc305e3 to your computer and use it in GitHub Desktop.
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.
// 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