logologo

Get Package Root

Jul 14, 2021 · 1min

When you want to get the real file path of a certain package, you could use require.resolve to fetch their main entry path.

> require.resolve('vite')
'/Users/.../node_modules/vite/dist/node/index.js'

> require.resolve('windicss')
'/Users/.../node_modules/windicss/index.js'
> require.resolve('vite')
'/Users/.../node_modules/vite/dist/node/index.js'

> require.resolve('windicss')
'/Users/.../node_modules/windicss/index.js'

However, when you want to get the root directory of the package, you will find the result of require.resolve could vary based on different packages’ configurations.

A trick for this is to resolve the package.json instead, as the package.json is always located at the root of the package. Combining with path.dirname, you could always get the package root.

> path.dirname(require.resolve('vite/package.json'))
'/Users/.../node_modules/vite'
> path.dirname(require.resolve('vite/package.json'))
'/Users/.../node_modules/vite'

Update: or you can use my package local-pkg now :)

CC BY-NC-SA 4.0 2021-PRESENT © Anthony Fu