Reputation: 71
I need to require() method to load modules from a folder nonother that node_modules folder. Is there a way to do that without using any npm libraries.
EX- There is an age folder inside the modules folder with an index.js file. I need to import that module like
const age = require('age')
without giving the relative path of the module.
Upvotes: 1
Views: 544
Reputation: 276596
Is there a way to do that without using any npm libraries.
The answer to that sort of thing is always "yes" because those libraries are written in JavaScript.
I would warmly recommend against it and for standard approaches (like using yarn workspaces and declaring age
as a proper local npm module) but you can always do something like a require hook:
const originalRequire = Module.prototype.require;
Module.prototype.require = function moduleRequire(id) {
if(id === 'age') {
return require('./modules/age');
}
return originalRequire.call(this, id);
}
Or add your local modules
folder to the NODE_PATH
environment variable so it finds it there.
Neither of these are good options and I recommend against both of them.
It is better to stick to the standard modus operandi and vendor and consume "proper" npm modules.
Upvotes: 1