Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to require.resolve the package directory?

Tags:

node.js

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')?

like image 768
mpen Avatar asked Jun 01 '17 18:06

mpen


People also ask

What is __ Dirname in node?

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.

How do I use require in node JS?

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).

What is Node_path?

NODE_PATH is: a process environment variable. that contains a search path value (one or more directory with the linux or windows path separator)


1 Answers

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.

like image 200
mpen Avatar answered Oct 25 '22 11:10

mpen