What is resolve-pkg?
The resolve-pkg npm package is used to resolve the path of a package regardless of where it is located in the node_modules hierarchy. This is particularly useful in monorepos or when dealing with nested dependencies.
What are resolve-pkg's main functionalities?
Resolve Package Path
This feature allows you to resolve the absolute path of a package. The code sample demonstrates how to use resolve-pkg to find the path of 'some-package'.
const resolvePkg = require('resolve-pkg');
const packagePath = resolvePkg('some-package');
console.log(packagePath);
Resolve Package Path with CWD
This feature allows you to resolve the package path starting from a specific directory. The code sample shows how to specify a custom current working directory (cwd) for the search.
const resolvePkg = require('resolve-pkg');
const packagePath = resolvePkg('some-package', { cwd: '/path/to/start/search' });
console.log(packagePath);
Other packages similar to resolve-pkg
resolve
The 'resolve' package is a dependency resolver that can find the full path to a module from a given starting point. It is more general-purpose compared to resolve-pkg, which is specifically designed for resolving package paths.
pkg-dir
The 'pkg-dir' package finds the root directory of a Node.js project or a package. While resolve-pkg focuses on resolving the path to a specific package, pkg-dir is useful for finding the root directory of the current project.
find-up
The 'find-up' package searches for a file or directory by walking up parent directories. It is more versatile in terms of finding various types of files, whereas resolve-pkg is specialized in resolving package paths.
resolve-pkg
Resolve the path of a package regardless of it having an entry point
Some packages like CLI tools and grunt tasks don't have a entry point, like "main": "foo.js"
in package.json, resulting in them not being resolvable by require.resolve()
. Unlike require.resolve()
, this module also resolves packages without an entry point, returns null
instead of throwing when the module can't be found, and resolves from process.cwd()
instead __dirname
by default.
Install
$ npm install --save resolve-pkg
Usage
const resolvePkg = require('resolve-pkg');
resolvePkg('grunt-svgmin/tasks', {cwd: __dirname});
require.resolve('grunt-svgmin/tasks');
API
resolvePkg(moduleId, [options])
moduleId
Type: string
What you would use in require()
.
options
cwd
Type: boolean
Default: process.cwd()
Directory to resolve from.
Related
- resolve-cwd - Resolve the path of a module from the current working directory
- resolve-from - Resolve the path of a module from a given path
- req-from - Require a module from a given path
- req-cwd - Require a module from the current working directory
- lazy-req - Require modules lazily
License
MIT © Sindre Sorhus