While specifying local modules as npm package dependencies shouldn’t be done in production or published packages. Sometimes, when doing development locally, you may want to use local modules that are not published to the npm registry.
For this to work my-project
must be configured as a module with its own package.json
, see creating NodeJS modules in NPM’s docs for more on this.
Typically, you would specify dependencies in your package.json
using package names that can be resolved from the npm registry.
Since npm 2.0, local dependencies are supported natively, as per danilopopeye’s answer on StackOverflow.
There are a few approaches you can use;
1. Use npm install with File Path:
You can use the file path directly in the dependencies
section of your package.json
.
{
"name": "my-project",
"dependencies": {
"bar": "file:../path/to/my-module"
}
}
Any of the following paths are also valid:
../path/to/my-module
~/path/to/my-module
./path/to/my-module
/path/to/my-module
2. Use npm link:
If you want to simulate the behavior of a package without publishing it to the npm registry, you can use the npm link
command.
- Navigate to your local module directory:
cd /path/to/my-module
- Run
npm link
. This will create a global symlink for your local module. - Navigate to your project directory:
cd /path/to/my-project
- Run
npm link my-module
. This will create a symlink in your project’snode_modules
that points to your local module.
Now, you can use the local module in your project’s code as if it were a regular npm package.
3. Use Git Repositories:
If your local module is version-controlled using Git, you can specify it as a dependency using a Git URL.
{
"dependencies": {
"local-module": "git+file:///path/to/my-module.git"
}
}
Get latest updates
Since npm install
copies my-module
into node_modules
, changes in my-module
‘s source will not automatically be seen by the dependent project.
There are two ways to update the dependent project with
- Update the version of
my-module
and then usenpm update
: As you can see above, thepackage.json
“dependencies” entry does not include a version specifier as you would see for normal dependencies. Instead, for local dependencies,npm update
just tries to make sure the latest version is installed, as determined bymy-module
‘spackage.json
. - Reinstall using
npm install
. This will install whatever is atmy-module
‘s source path, even if it is older, or has an alternate branch checked out, whatever.
Always remember to document any unusual dependency management approaches for the benefit of your team and future maintainers.