DEV Community

Cover image for Testing the package live before publish with npm link
Reihaneh Dastres
Reihaneh Dastres

Posted on

Testing the package live before publish with npm link

Regarding the challenges I have been engaged in for a long time, one of them was live testing of packages before deploying them to the npm environment. Since the projects were heavy and numerous, using Monorepo was not a viable option.
I decided to use the npm link, but there was a problem. With every change, I had to rebuild (because if I wanted to apply live changes to the packages, I would get an "invalid hook" error) and this drained my energy. Eventually, I found a solution.

What is npm link?

It is a command in npm that allows you to temporarily link your software packages to other projects. By using this command, you can observe the changes made to a package in other projects that are linked to it without the need to publish and reinstall the package every time.
In other words, with npm link, you can use a package you are currently developing as a linked package in another project, and the changes you make will immediately be visible in the relevant projects. This is very useful when you need to work on multiple projects simultaneously that require the use of a common package.

Prerequisites and Configurations:

To test a package with npm link, you need to consider two points:
First, the package should not be installed in the project.
Secondly, you need to modify this part of the package's package.json as follows:

before:

Image description

after:

Image description

If you look carefully, you will see that instead of ./dist/packageName.es.js, this is ./src/index.jsx.
In this way, we are trying to make them understand that our criterion is index file changes, not build changes

packageName means the name of the local package

Third, in the vite.config of the main project, tell it to use the project's own React, not the React package, with this code.

Image description

import path from "path"
resolve: {
alias: {
react: path.resolve(__dirname, "./node_modules/react"),
},
},

I use Vit, if you use Webpack, you must define the React path from the node module.

how to use

Execute this command in the package

npm link

Run the following command in the project

npm link packageName

packageName means the name of the local package
Now, any changes you make will be applied live without the need to run a command

When the test is finished, link the package from the project and you can use the published version after publication.

npm unlink packageName

Top comments (2)

Collapse
 
kirilldedeshin profile image
Kirill Dedeshin

Thanks for your work

Collapse
 
basiiil profile image
Reihaneh Dastres

you're welcome