If you develop a modular application for Node.js, you may end up having lots of local node modules which you don’t want to publish yet. Nevertheless, you need to use them pretty much like any of the published node modules in order to ease the subsequent publishing. This means:
- requiring modules by the module name in your code:
var myModule = require('my-module');
- declaring dependencies in your app using the module name as if it was published
Additionally, it’s good to be able to edit the modules’ code and see the changes in your app immediately without re-installation of modules.
These requirements discard the following solutions:
- using relative path to require a local module:
var myModule = require('../../local-folder/my-module')
- using local npm installs:
npm install ../../local-folder/my-module
The first possible solution would require changing your code if modules get published. And the second one requires re-installing modules each time when there are any changes to them.
The 3rd working solution exists - npm linking! The linking process consists of two steps:
- declaring a module as a global link by running
npm linkin the module’s root folder
- installing the linked modules in your target module(app) by running
npm link <module-name>in the target folder
This works pretty well unless one of your local modules depends on another local module. In this case, linking fails because it cannot find the dependent module. In order to solve this issue, one needs to link the dependent module to the parent module and then install the parent into the app. For example, if given the following module structure:
modules/moduleA modules/moduleB -> depends on moduleA app/
one has to use npm links in the following order in order to install moduleB in the app:
cd modules/moduleA npm link cd modules/moduleB npm link moduleA npm link cd app/ npm link moduleB
And if there are lots of inter-dependent modules, doing this manually becomes complicated. So it’s time to automate. Meet the npm-link-shared project. It provides a cli command that installs all modules from a local folder into the target app. It works bases on a couple of assumptions:
- the source folder contains all modules which have to installed in a target folder
- the name of module folders matches the module name in the package.json
npm-link-shared /home/user/internal_modules/ /home/user/my-project
See the project docs on Github for more details.
Thanks for reading.