Anthony Fu @

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

> require.resolve('windicss')

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

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

> comment on mastodon / twitter
CC BY-NC-SA 4.0 2021-PRESENT © Anthony Fu