DEV Community

Cover image for Private NPM Packages the Easy Way
Ben Force
Ben Force

Posted on • Originally published at justwriteapps.com on

Private NPM Packages the Easy Way

Suppose you just wrote an amazing node module that you want to break off into a package so it can be reused. The problem is that it contains some super-secret company stuff that can’t be shared and you can’t, or don’t want to, create a private npm organization. So what do you do now?

Believe it or not, if you’re using private git repositories then you already have everything that you need.

Installing packages from git

Installing packages with git is actually really easy, if you use github, gitlab, bitbucket. npm install just requires a special package name to install from git. The format is SERVICE:user/repo.

So if your username is stan and you’re trying to install the willzyx repo from gitlab, then execute the following command:

npm install gitlab:stan/willzyx
Enter fullscreen mode Exit fullscreen mode

How about versions?

To install a specific tag or branch, add #NAME to the end of the package name. If you’re using npm version to update your package version, then you can add #semver:^1.0 to install the latest version of 1.x.

What about complex packages?

Sure, that’s great for plain-old javascript packages, but what if you’re using something fancy like Typescript? How do you build the package without checking in the build artifacts to your repo?

The scripts section of package.json has a few special scripts that run as part of specific npm commands. The one you want to define is prepare. This script is run after the package is installed.

To continue the typescript example, you could use the following prepare script:

"prepare": "node_modules/.bin/tsc"
Enter fullscreen mode Exit fullscreen mode

Any development dependencies will be installed before the script is run, and cleaned up after.

Now that it’s built, how do I cleanup?

This one is also pretty easy if you use git. Just like git has the .gitignore file, npm has a .npmignore file. .npmignore has the same format, and is applied after the prepare script has finished. This means you can add the source directory to .npmignore and it will magically disappear after you’ve installed the package.


Hopefully this article has encouraged you to create some packages of your own. If you have any other tips that I may have missed, please share them with me in the comments or on twitter.


References

Top comments (1)

Collapse
 
p4l3k1n6 profile image
Pale King

I am finding the statement “prepare” for 5hrs. Thanks