Let us consider an hypothetical scenario where we have project foo
with the below directory structure:
1 2 3 4 5 6 7 |
|
Let us say that src/component
in dependent on lib/util.js
, in current world one would have to do the below to require
the util
in their component
1
|
|
The nesting for those realtive paths ../../
gets more complex as the directory structure gets more deeper.
For our rescue the module
object of node got an addition of createRequireFromPath
method in v10.12.0
, which accepts a
filename
to be used to construct the relative require function.
and return a require
function.
This can help in doing the below in our src/component
, rather than dealing with relative paths.
1 2 3 |
|
So, any files in ../../lib
can now be just required as requireLib(<absPath>)
instead of dealing with relative paths.
The heart of createRequireFromPath
looks like:
1 2 3 4 5 6 |
|
Meanwhile, MylesBorins has a proTip for us:
omfg
— sMyle (@MylesBorins) March 24, 2019
`const require = createRequireFromPath('.');`
... just works 😇