Feb 18 '22 ~ 32 ~ 2 mins

Use npm pack to test your packages locally

When working with npm packages you often want to test your package without having to publish it to npm. This enables you to have a quicker feedback loop and keeps the number of published versions to a minimum.

This is where npm pack comes in.

First: Build your Package

Before you can use npm pack you must first build your package. So run your build command and check that this has completed successfully. In my use case, for @ag-grid-community/angular the command is:

community-modules/angular$ npm run build

Second: Locate your Build Artifacts package.json

The important part of this step is to run npm pack in the correct folder location where the build artifact package.json is located. Depending on your project that may be the same folder as where you ran your build. For me though, with this Angular library that means navigating into the dist/ag-grid-angular folder as that is where the Angular library builds to.

community-modules/angular$ cd ./dist/ag-grid-angular

Third: Pack your artifacts

Now it is time to package our build artifacts to enable us to produce a package that mimic what would be published to npm. We tell npm to pack it to our user folder ~ for ease.

community-modules/angular/dist/ag-grid-angular$ npm pack --pack-destination ~

After this runs you will have the following file.

~/ag-grid-community-angular-27.0.0.tgz

Fourth: Point package.json to your file

Now that we have this package we can test it in our application. To do this we update our package.json to point to the file that we produced in the previous step.

"dependencies": {
  "@ag-grid-community/angular": "file:~/ag-grid-community-angular-27.0.0.tgz"
}

Then make sure you remember to re-install your packages after this update.

npm install

Fifth: Test your package in your application

Now you can run your application using your packed dependency. This enables you to test your package without having to publish it to npm for all the world to see.

Not only does this save us time by giving us a quicker feedback loop but it keeps our published packaged versions clean. This approach also gives us more confidence that our library is working as expected when installed into an application. We are more closely mimicking our users as opposed to testing against the raw source files.

Happy testing!


Stephen Cooper - Senior Developer at AG Grid Follow me on Twitter @ScooperDev or Tweet about this post.


Headshot of Stephen Cooper

Hi, I'm Stephen. I'm a senior software engineer at AG Grid. If you like my content then please follow / contact me on Twitter and say hello!