July 10, 2024

How to test your npm package locally

RMRohan Mayya

A mistake we made initially with Toolify's npm package was not testing our npm packages locally. We quickly resolved that, but not without some setup work. Here's the best way to test it.

Once you've created your library, (and you have your package.json setup), in that folder in your terrminal, run

npm pack

This command will generate an artifact file with this format package-x-x-x.tgz. This artifact is the same thing that's uploaded on to npm when you publish your package.

Now in the package.json of another project where you want to test the package, add this in the dependencies:

{
dependencies: {
"@package": "/path/to/your/package-x-x-x.tgz"
}
}

To use the package, you can do: import "@package/dist/index.css"

We use tsup to package the UI library.

Bonus

If you want to avoid imports like:

import { Badge } from "@trytoolify/ui/dist/src/components/ui/badge";

and instead have imports like:

import { Badge } from “@trytoolify/ui”;

Then all you need to do is make sure your exports in your library's package.json looks like this:

{
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"files": [
"dist"
],
"exports": {
"./components/ui/*": {
"import": "./dist/src/components/ui/*.mjs",
"require": "./dist/src/components/ui/*.js"
},
},
}

(The above is assuming you have, for example, components in src/components.)

Ready to build your tools?

Use Toolify today