Create require
that's binded to a directory different from where your code is located.
For example:
const requireFrom = require("require-from-path")("/some/other/dir");
const foo = requireFrom("./foo.js");
const bar = requireFrom("bar");
Above code will:
require
the file/some/other/dir/foo.js
- Search and
require
the modulebar
starting at/some/other/dir
.
Given the directory structure below with two NodeJS apps:
app1
|-+ foo
| +-- index.js
| +--+ node_modules
| +--+ x
| + ...
app2
|-+ bar
| +-- index.js
| +--+ node_modules
| +--+ y
| + ...
When you call require("x")
in /app1/foo/index.js
, NodeJS will search and find module x
there.
Now from the same file, if you want to resolve the module y
under the directory /app2/bar
, you have to use an absolute or relative path directly pointing to y
, and you may have to do some searching, probably re-implementing Node's module searching algorithm if you don't know exactly where y
could be.
However, in the file /app2/bar/index.js
, it can just do require("y")
and Node would automatically find the module for it, because that file is at the location where y
is under.
What if from the file /app1/foo/index.js
, you can call require
as if you were at the directory /app2/bar
, then you would be able to utilize Node's module searching automatically.
To achieve this, most other implementations choose to re-implement Node's module searching algorithm.
This module's approach is to tap into Node's module
and let it do the work.
$ npm install require-from-path --save
A single function is exported.
- If you call it with just
dir
, then it returns arequire
function that's been binded to the directorydir
. You can use it to load any module as if you are atdir
.- You can also call
require.resolve
with the same effect.
- You can also call
- If you call it with
dir
and arequest
, then it will load and return the modulerequest
as if atdir
.
const requireFromPath = require("require-from-path");
// get back a require binded to /another/dir
const requireFromPathAnother = requireFromPath("/another/dir/");
const modXPath = requireFromPathAnother.resolve("modX");
const modX = requireFromPathAnother("modX");
// load modY at /another/yet/dir directly
const modY = requireFromPath("/another/yet/dir", "modY");
Apache-2.0 © Joel Chen