'How to require.resolve the package directory?

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



Solution 1:[1]

same as the solution above, I found you can do slightly better with

import findRoot from 'find-root';

findRoot(require.resolve('babel-runtime'))

still hacky, but will work even if package.json is not in the "exports" field.

that said, actually this would fail for babel-runtime.. huh.. so it won't work for the original question

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Uri Kutner