Assuming my folder structure is something like:
project/
-- package.json
-- index.mjs
-- lib/
-- config/
-- index.mjs
When I used require()
natively in node I could reference a local module using a bare import like:
const x = require('config')
because I added the root of my library folder to the NODE_PATH
environment variable. (assuming of course when I was using cjs/require the extension would have been .js
)
When I try to do that using native es6 modules (mjs) like:
import x from 'config'
I get the error:
Error [ERR_MODULE_RESOLUTION_LEGACY]: config not found by import in [SOME_ABS_PATH]/index.mjs. Legacy behavior in require() would have found it at [SOME_ABS_PATH]/lib/config/index.mjs
Anyone know how to solve this? Or what the future is for dealing with relative paths for local module resolution within the node native es6 module system?
Only resource I've found on this so far is from here http://2ality.com/2017/09/native-esm-node.html stating:
Path resolution works slightly differently: ESM does not support NODE_PATH and require.extensions. And its specifiers always being URLs also leads to a few minor differences.
And on the error message below ERR_MODULE_RESOLUTION_LEGACY
- google showed up literally nothing.
Okay, so a colleague (thanks @robin-balmforth ) gave me the answer:
From https://nodejs.org/api/esm.html#esm_no_node_path it says:
Notable differences between import and require No NODE_PATH NODE_PATH is not part of resolving import specifiers. Please use symlinks if this behavior is desired.
And from something even more canonical:
All of the following will not be supported by the import statement:
$NODE_PATH $HOME/.node_modules $HOME/.node_libraries $PREFIX/lib/node Use local dependencies, and symbolic links as needed.
So instead of me setting the NODE_PATH environment variable I have to setup a symlink like:
ln -s ../lib node_modules/lib
Seems to work fine yay.
We suppose the reason is for compatibility with the browser implementation of es6 modules?
There is some discussion on the reasoning behind this change from https://github.com/bmeck in this node-eps issue https://github.com/nodejs/node-eps/issues/11 like:
The solution is not a workaround, it is how path resolution works. Having a single flat namespace for "bare" path resolution is important.