You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
14 Hrs
50 Min
34 Seg
Curso de Fundamentos de Node.js

Curso de Fundamentos de Node.js

Oscar Barajas Tavares

Oscar Barajas Tavares

Creaci贸n de un Paquetes con NPM

6/20
Resources

Building packages in NPM is a fundamental skill for any Node.js developer who wants to share their solutions with the community. Learning how to build, test and publish a package not only enhances your professional profile, but also contributes to the JavaScript ecosystem, allowing other developers to leverage your code to solve common problems.

How to create an NPM package from scratch?

Creating an NPM package requires following a series of structured steps to ensure that our code is accessible and usable by other developers. In this case, we are going to build a package called "platzi-date" that will allow us to handle dates in two specific formats: timestamp and long format.

Initializing the project

To start creating our package, we need to follow these initial steps:

  1. Create a directory for our package:
mkdir platzi-datecd platzi-date
  1. Initialize Git for version control:
git init
  1. Initialize the NPM project with default configuration:
npm init -y

This last command will automatically generate a package.json file with the basic configuration that we will later modify according to our needs.

Structure and development of the source code

Once the project is initialized, it is time to create the file structure and develop the package functionality:

  1. Create the src folder for the source code.
  2. Create the main index.js file inside the src folder .

In our index.js file, we will implement the two main functions:

// Function to get the current timestampfunction getTimeStamp() { return Date.now();}
// Function to get the date in long formatfunction getLongTime(locale = 'en') { const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', timeZoneName: 'short' };  
 return new Date().toLocaleDateString(locale, options);}
// Export functionsmodule.exports = { getTimeStamp, getLongTime};

The getTimeStamp() function simply returns the current time value in milliseconds since January 1, 1970, using the native Date.now() method.

The getLongTime() function is more complex and allows us to format the current date in a long format, specifying the language using the locale parameter (which defaults to English). This function uses the toLocaleDateString() method of JavaScript, which accepts formatting options to customize the output.

Package documentation

A good package should always include clear documentation. We will create a README.md file:

# platzi-date
A utility to handle dates in timestamp and long time format.
 ##Install
 ````bashnpm install platzi-date.

This basic documentation explains the purpose of the package and how to install it.In a real package, it would be advisable to add usage examples, detailed API and any other relevant information.
 ### Configuring package.json
The ``package.json`` file is crucial for the release of our package.We must modify it to include important information:
 ````json{ "name": "platzi-date", "version": "1.0.0", "description": "A utility to handle dates in timestamp and long time format", "main": "src/index.js", "keywords": ["date", "time", "timestamp"], "author": "Your Name", "license": "MIT"}

The most important fields are:

  • name: The unique name of our package
  • description: A brief description of the functionality
  • main: The path to the main file of the package
  • keywords: Keywords to facilitate the search
  • author: Your name or identifier
  • license: The license type (MIT is common for open source projects)

How to test an NPM package locally?

Before publishing our package, it is essential to test it locally to make sure it works correctly. NPM provides a tool called npm link that allows us to create a symbolic link to our local package.

Creating the symbolic link

To create the link, follow these steps:

  1. Inside our package directory, we run:
npm link
  1. In the project where we want to test the package, we execute:
npm link platzi-date

This creates a symbolic link in the node_modules folder of our project, pointing to the local package we are developing.

Testing the package

To test our package, we create a test file in our main project:

// date.jsconst dateFormatter = require('platzi-date');
// Get current timestampconsole.log(dateFormatter.getTimeStamp());
// Get date in Spanish (default format)console.log(dateFormatter.getLongTime());
// Get date in Englishconsole.log(dateFormatter.getLongTime('en-US'));

When running this file with Node.js:

node date.js

We should see three outputs:

  1. A number representing the current timestamp.
  2. The current date in Spanish long format
  3. The current date in English long format

If everything works correctly, it means that our package is ready to be published.

What considerations should we have before publishing?

Before publishing our package in NPM, it is important to make some final checks:

  1. Check the code: Make sure that there are no errors, types or strange elements.
  2. Check the documentation: Check that the README.md is clear and contains all the necessary information.
  3. Check the package.json: Verify that all fields are correctly configured.
  4. Test thoroughly: Ensure that all functionality is working as expected.

It is essential to perform these checks because once the package is published, although new versions can be published, the original version will be registered in NPM and could be downloaded by other developers.

Creating and publishing packages in NPM is a great way to contribute to the development community and share useful solutions. With this process, you have learned how to create a simple but functional package for date management. What other types of utilities do you think you could develop and share with the community? Share your ideas in the comments!

Contributions 0

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?