Home >Web Front-end >JS Tutorial >How to Create Your First Package and Publish It in NPM
Publishing our own package on NPM (Node Package Manager) is a great way to share, learn the code with the community or facilitate reuse in our own projects. In this guide, we will learn step by step how to create, configure and publish our first package in NPM.
An NPM package is a JavaScript module that you can install and use in Node.js projects. It can be as simple as a reusable function or as complex as an entire library.
Before we start, we have to make sure we meet the following requirements:
Node.js and NPM installed: Download and install from Node.js.
NPM account: Register at npmjs.com.
Code editor: Like VS Code, to write and organize your project.
Step 1: Create a folder for your package
Open your terminal and create a folder:
mkdir mi-primer-paquete cd mi-primer-paquete
We open the folder in our code editor:
code .
Step 2: Initialize the project
We run the following command to create a package.json file:
npm init
Answer the questions or use npm init -y to accept the default values.
Check the generated package.json file. It should look something like this:
{ "name": "mi-primer-paquete", "version": "1.0.0", "description": "Mi primer paquete publicado en NPM", "main": "index.js", "scripts": {}, "keywords": ["npm", "paquete", "tutorial"], "author": "Tu Nombre", "license": "MIT" }
Step 3: Create the main file
Create a file called index.js in the root of the project:
touch index.js
Add a simple function as an example:
function holaMundo() { return "¡Hola, mundo!"; } module.exports = holaMundo;
Step 1: Log in to NPM
Run the following command in your terminal and follow the instructions to log in:
npm login
Step 2: Publish the package
Run this command to publish your package to NPM:
npm publish
Ready! Now your package will be publicly available on NPM.
To make sure your package works, test it by installing it in another project:
Create a new folder for tests:
mkdir prueba-paquete cd prueba-paquete
Initialize a project and then install the package:
npm init -y npm install mi-primer-paquete
Use the package in a file:
const holaMundo = require("mi-primer-paquete"); console.log(holaMundo()); // ¡Hola, mundo!
If we need to make changes, simply update the code, increment the version in package.json (e.g. change "version": "1.0.0" to "version": "1.0.1") and republish it:
npm publish
The above is the detailed content of How to Create Your First Package and Publish It in NPM. For more information, please follow other related articles on the PHP Chinese website!