How to create, publish and use private NPM packages

After a long time working with different package systems I decided to migrate all my packages and dependencies to NPM. And the result couldn’t have been better.

When NPM reached the 5.x version they included a lot of things that improved the performance, speed and security of the packages.

There’re two commands that I specially like a lot.

npm outdated
npm audit

Working with NPM audit & NPM outdated commands

These two commands give you the power to easily keep all your dependencies up to date and perform security audits. Really simple and powerful, let’s take a look.

Imagine you’re using lodash library in your project, version 4.13.0.

Let’s try npm outdated command:

$ npm outdated
Package  Current   Wanted   Latest  Location
lodash    4.13.0  4.17.11  4.17.11  @moises/test-private-npm

As you can see in the output, NPM is telling you the current version you’re using the wanted and the latest. So, in a glance, you can check which dependencies are outdated for your project and easily update them to a recent version.

Let’s try now npm audit command:

$ npm audit
                                                                                
                       === npm audit security report ===                        
                                                                                
# Run  npm install lodash@4.17.11  to resolve 1 vulnerability
┌───────────────┬───────────────────────────────────────────────┐
│ Low           │ Prototype Pollution                           │
├───────────────┼───────────────────────────────────────────────┤
│ Package       │ lodash                                        │
├───────────────┼───────────────────────────────────────────────┤
│ Dependency of │ lodash                                        │
├───────────────┼───────────────────────────────────────────────┤
│ Path          │ lodash                                        │
├───────────────┼───────────────────────────────────────────────┤
│ More info     │ https://nodesecurity.io/advisories/577        │
└───────────────┴───────────────────────────────────────────────┘


found 1 low severity vulnerability in 1 scanned package
  run `npm audit fix` to fix 1 of them.

The audit command is running a security report over your all dependencies and it’s explaining you the problems found and how to solve them. Pretty handy, huh?

Creating your NPM Account

Now that we covered these two awesome NPM tools to manage easily your dependencies, let’s have a look at how we can get our projects, create NPM private packages for them and publish them as a private package to be used later on as a dependency in other projects.

First thing you’ll need is go to this page to create your NPM account:

https://www.npmjs.com/signup

npmjs-private-package

Once you have your NPM account created, you can login from your command line tool using this command:

$ npm login

username: [YOUR-NPM-ACCOUNT-USERNAME]
password: [YOUR-NPM-ACCOUNT-PASSWORD]

Just as a validation check your login information using:

$npm whoami
[YOUR-NPM-ACCOUNT-USERNAME]

It will return your NPM account username logged in.

Creating your first private NPM package

Let’s create a new directory in your machine and move to there.

$ mkdir test-private-npm
$ cd test-private-npm

After that, we need to convert that directory into a real NPM package just using the init command and set the scope of this package as private.

$ npm init --scope=@[YOUR-NPM-ACCOUNT-USERNAME]

This command will create a package.json file in your directory and will set up that package as a private package.

After answering some few questions you’ll see your package.json file created with a content similar to this:

{
  "name": "@moises/test-private-npm",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Moises Belchin <moisesbelchin@gmail.com>",
  "license": "MIT"
}

As you can see the name of the package starts with @ this indicates that is a private package.

If you have an organization created instead of using your @[YOUR-NPM-ACCOUNT-USERNAME] you can set the name as @[YOUR-NPM-ORGINAZATION] this way you’re package will be private and will be shared across all the members in your organization.

Now you can create the index.js main file of your package and add some content to it.

$ touch index.js

Open the index.js file with your favorite editor and add this information:

const
  path = require('path');

console.log( `You're working in this directory: ${path.join( __dirname, '/' )}` );

You can run it using this command:

$ node index.js

You're working in this directory: /Users/moises/test-private-npm/

Publishing your first private NPM package

Great!, we have our project, we have our package.json file created, now it’s time to publish it. Just as simple as running this command:

$ npm publish

NPM will read your package.json file and will take the contents of the directory to publish your package as private package into your NPM account.

NPM will show you the process and the result of the publishing.

$ npm publish
npm notice 
npm notice 📦  @moises/test-private-npm@1.0.0
npm notice === Tarball Contents === 
npm notice 312B package.json
npm notice 115B index.js    
npm notice === Tarball Details === 
npm notice name:          @moises/test-private-npm             
npm notice version:       1.0.0                                   
npm notice package size:  421 B                                   
npm notice unpacked size: 427 B                                   
npm notice shasum:        c58d487a9a5dbb4906b6d8bee58c37fdde70901c
npm notice integrity:     sha512-na6eCo/rRbRoy[...]i2YqkZJVO3+0w==
npm notice total files:   2                                       
npm notice 
+ @moises/test-private-npm@1.0.0

Using your private NPM packages

We have a new private package created and published, now it’s time to start using it.

Let’s create now a new project directory and run NPM there to use our private NPM package @moises/test-private-npm.

$ mkdir test-using-private-npm
$ cd test-using-private-npm
$ npm init -y

Now it’s time to install our private NPM package recently created as a dependency.

$ npm install --save @moises/test-private-npm

If you run that command NPM will look for @moises/test-private-npm package and will save it as a dependency in your new project. Let’s have a look.

$ npm install --save @moises/test-private-npm
npm WARN test-using-private-npm@1.0.0 No description
npm WARN test-using-private-npm@1.0.0 No repository field.

+ @moises/test-private-npm@1.0.0
added 2 packages from 3 contributors and audited 2 packages in 2.562s
found 0 vulnerabilities

As you can see in the output there’re some warnings about description and repository fields not being found in the package.json file. Nothing to worry about.

NPM has installed our package @moises/test-private-npm@1.0.0 and add it to the package.json file in the dependencies section. Let’s check its content:

{
  "name": "test-using-private-npm",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "@moises/test-private-npm": "^1.0.0"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Now let’s run the index.js file from the installed dependency.

$ node node_modules/\@moises/test-private-npm/index.js

You're working in this directory: /Users/moises/test-using-private-npm/node_modules/@moises/test-private-npm/

As you can see is executing the same file we published on our private package.

Creating & Publishing a new version of your private NPM packages

It’s really simple and easy to work this way. What would happen if we make some changes in our private package ? How do we notify projects that are using our package to be upgraded ?

To answer these questions you need to modify your project, create a new version and publish it to NPM.

After that you can use npm outdated command on your projects and it’ll inform you that there’s a new version available.

Let’s do it !

Go to your private package directory.

$ cd test-private-npm

Make any change, open index.js file and add this code into it:

console.log(' ====================================' );
console.log(' This is a new version !!!!! ');
console.log(' ====================================' );

The file will look like this:

const
  path = require('path');

console.log( `You're working in this directory: ${path.join( __dirname, '/' )}` );

console.log(' ====================================' );
console.log(' This is a new version !!!!! ');
console.log(' ====================================' );

Now you need to change the version of this private NPM package. You can directly change it in the package.json file or you can use npm version command.

$ npm version 1.0.1

v1.0.1

And after that, you can publish this new version to NPM by running:

$ npm publish

npm notice 
npm notice 📦 @moises/test-private-npm@1.0.1
npm notice === Tarball Contents === 
npm notice 312B package.json
npm notice 272B index.js 
npm notice === Tarball Details === 
npm notice name: @moises/test-private-npm 
npm notice version: 1.0.1 
npm notice package size: 446 B 
npm notice unpacked size: 584 B 
npm notice shasum: 8a98263b8d621f48939f3194e81a1ce336eb1ecc
npm notice integrity: sha512-TCcc4DePeNjJY[...]PiN0yH0Srjkjw==
npm notice total files: 2 
npm notice 
+ @moises/test-private-npm@1.0.1

You can see the new version number 1.0.1 published.

Keeping your NPM dependencies up to date

Now that you have published a new version of your NPM private package. You can go the projects in which you’re using this new dependency and use the npm outdated command to see if there’s something new to upgrade.

$ cd test-using-private-npm
$ npm outdated

Package Current Wanted Latest Location
@moises/test-private-npm 1.0.0 1.0.1 1.0.1 test-using-private-npm

As you can see it’s informing you about a new version available. Let’s update then.

$ npm update

+ @moises/test-private-npm@1.0.1
updated 1 package and audited 2 packages in 3.001s
found 0 vulnerabilities

NPM will inform you about the new version recently updated and if it found any vulnerabilities on the new version.

Now as we did before you can run the new index.js file and you’ll see the new code running.

$ node node_modules/\@moises/test-private-npm/index.js 


You're working in this directory: /Users/moisesbelchin/Sites/test-using-private-npm/node_modules/@moises/test-private-npm/
====================================
This is a new version !!!!! 
====================================

 

One thought on “How to create, publish and use private NPM packages

Add yours

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: