Simplify your NPM package development journey

In this article, we will explore how to streamline the development of an NPM package using the npm link command. This command enables the creation of a symbolic link from the package under development to the package or application that will use it.

Let’s say we have a package that we want to develop concurrently with an application that utilizes it. There are several ways to do this:

  • Copy-pasting the package into the node_modules directory, which is too repetitive.
  • Using git submodules, which complicates the development process.

The best solution is to use npm link. This command creates a symbolic link from the package you are creating to the node_modules directory of the application that will use it. This way, we can separate the application and the package we want to use on the application into two different directories. It also allows us to use git (without using submodules) on both the package we are creating and the application.

Here’s how to use the npm link command. First, let’s create a module that displays “Hello!” in the console. Then, we’ll create an application that will use the package we’ve created to display the message “Hello!” in the console.

First, let’s place our module in a directory called hello.

$ mkdir hello
$ cd hello
$ touch index.js
$ npm init

npm init initializes an npm package. This command generates a package.json file that contains all the information about the package (author, name, description, dependencies, etc.). Now, let’s create the function that says hello in the index.js file:

module.exports = "Hello!"

Next, we’ll create the application that will use it:

cd ..
mkdir hello-app
cd hello-app
touch index.js
npm init

In the index file, we’ll use the hello module:

const hello = require('hello');
console.log(hello);

Now, let’s create a symbolic link from the package to the application that will use it. To do this, first, simply type npm link in the root directory of the package that displays hello. Then, in the directory of the application that will use it, just enter the command npm link hello where “hello” is the name of the package we previously created.

To use npm link, it is necessary for the modules to have a valid package.json file.

The npm link command can be used on all operating systems, even if Windows operating systems do not natively support symbolic links.

Conclusion

npm link is available on all versions of NPM. The npm link command greatly simplifies the package development process because it is very easy to use. I hope this article has helped you. Feel free to leave a comment. In a future article, I will show you how to publish a package to the NPM repository.