In this tutorial, we are going to see how to create and publish our own NPM packages, either to a public or private registry.
As we have seen in the course, NPM packages are the fundamental unit of reusable code in the JavaScript/Node.js ecosystem.
So it’s very likely that at some point you’ll want to create your own NPM packages and upload them to either a public or private repository.
Furthermore, it’s very useful and simple. So let’s get to it 👇.
How to create an NPM package
To create our own package, we start by creating a Node.js project. To do this, create a new folder for your NPM package.
mkdir mi-paquete cd mi-paquete
And initialize the project with
npm init
Once your project is initialized, we can start writing your library’s code. For example, create a file named index.js (or the name you choose) and add your code,
function greeting(name) {
return `Hello, ${name}!`;
}
module.exports = greeting;
This is a very simple example, but you can create much more complex packages that include several functionalities, classes.
Configure the package.json file
Now we need to configure the package.json file, which contains all the information about your package and its dependencies.
{ “name”: “mi-paquete”, “version”: “1.0.0”, “description”: “Un paquete simple de ejemplo que dice hola”, “main”: “index.js”, “scripts”: { “test”: “echo “No tests specified"" }, “author”: “Tu nombre”, “license”: “MIT” }
- name: Your package’s name (must be unique on NPM)
- version: The version of your package
- main: The main file of your package (for example,
index.js). - dependencies: The dependencies needed for your package to work (if any).
- scripts: The scripts you can run with NPM, such as tests or project build.
Test the package locally
Before publishing your package, it’s generally a good idea to test that it works (so it doesn’t crash). To test your package locally, we can install it directly from the folder where you created it.
Create a new project (outside the folder where you created the package), and install the project from the folder by doing:
npm install /ruta/a/tu/paquete
This will install your package as a local dependency. Then, you can test it in this project’s code:
const greeting = require('my-package');
console.log(greeting('World'));
This is not very clean. Use it only to test that the package works correctly, but not as a production solution.
Publish the package to NPM
Once you are sure everything is working correctly, we can now publish it to NPM so it’s available for download.
First, if you don’t have an NPM account, create one at https://www.npmjs.com/signup. Then, log in from the terminal with:
npm login
Once you have logged in (username, email, and password) you can publish your package using the following command:
npm publish
This will upload your package to NPM and it will be available for others to install with:
npm install mi-paquete
