require.resolve('babel-runtime')
returns an error because its package.json
does not contain a "main" field. However, I'm not interested in the main/entry file of the package, I want to get the directory of the package itself.
Usually that's located at ${__dirname}/node_modules/babel-runtime
, but it might not be if the node_modules
tree is flattened. So how can I resolve the directory of a package the same way Node knows where to look when you write something like require('babel-runtime/core-js/object/create')
?
It gives the current working directory of the Node. js process. __dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file.
You can think of the require module as the command and the module module as the organizer of all required modules. Requiring a module in Node isn't that complicated of a concept. const config = require('/path/to/file'); The main object exported by the require module is a function (as used in the above example).
NODE_PATH is: a process environment variable. that contains a search path value (one or more directory with the linux or windows path separator)
It occurred to me that if Node can resolve file paths even when "main" doesn't exist, then I can abuse that like so:
path.dirname(require.resolve('babel-runtime/package.json'))
i.e., resolve a file that you know to exist, and then work backwards from there. Kind of a hack, but it's the only solution I've found.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With