DEV Community

Cover image for Create & Publish a Node.js NPM Package in 7 Minutes
Hays Stanford
Hays Stanford

Posted on

Create & Publish a Node.js NPM Package in 7 Minutes

Why care about NPM?

NPM, or Node Package Manager, is the default package manager utilized by the infamous Node.js runtime environment for JavaScript.

Instead of downloading packages directly & placing them into your Node.js source directory while writing a bunch of quirky import statements, you can simply:

  • Run npm install PACKAGE_NAME to add the package to the /node_modules directory.

  • Add import VAR_NAME from 'PACKAGE_NAME'; to your source.

  • Utilize the package with the defined variable name, such as example() or example.includedFunction().

The vast majority of JS developers utilize NPM, or its faster kin Yarn, to install their packages in minutes.

If you’re looking to open-source a library for Node, you’ll want to ensure it is all published on NPM. Otherwise, it may fail to be seen at all.
Publishing to NPM

Publishing an NPM project

The neat thing about publishing a package to the NPM registry is that it’s about as simple as installing a package from the registry.

Open your CLI, type a few commands, then BOOM… your code is live. For a more descriptive approach, see the steps below.

  • You need to make sure the directory you're publishing is an NPM project. Do this by running npm init then complete the automatic prompts.

npm init

  • Ensure that any code you want in the library can be utilized by properly exporting it in Node. For our example, we’ll be exporting printMsg() from index.js as a simple test command:
exports.printMsg = function() {
 console.log('Here is our test message from our NPM package.')
}
  • Open up the generated package.json and make sure that the "main" key is set to the entry file for your library. Here’s an example using index.js:
{
  "name": "test-test-test-npm-package",
  "version": "1.0.0",
  "description": "A test npm package",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Hays Stanford",
  "license": "ISC"
}
  • Once you have everything setup as stated above, it’s time to publish! All you have to do is run npm publish from within the directory of your NPM project.

npm publish

If there are no errors, then you’re done! Your NPM package is officially published to the public NPM registry. It’s that simple…

If you want to see your NPM package in the public registry of NPM, you can do that by searching for it on www.npmjs.com.

view of test package on npmjs.com

The package created in this tutorial was named test-test-test-npm-package and you can view it by clicking here.

Hope this helps you guys! Let me know if there’s anything else you’d like to see, definitely DM me on Twitter. Click below to follow my Twitter:

Top comments (0)