In this article, we will learn how to develop and publish your own npm package (also called an NPM module).
There are many benefits of NPM packages, some of them are listed below:
- Reusable code
- Managing code (using versioning)
- Sharing code
The life-cycle of an npm package takes place like below:
1. Setup a Project: Setting up a project is required before doing anything.
- Install Node.js
- Create an npm account.
- Logging in to the npm account using npm login
2. Initializing a module: To initialize a module, Go to the terminal/command-line and type npm init and answer the prompts.
- In the version prompt, set it to 0.0.0. It initializes the module. If you keep it 1.0.0, it means that the current module version is the first major release to the potential downloaders. Of course, you don’t want the first major release to be only a blank slate and full of bugs.
- In the main prompt, choose the entry point of the module. Potential downloaders will use it as the entry point to the module. Note that the entry point is ‘src/index.js’ which is considered a standard practice these days to put your code in an ‘src’ directory.
- In the test command prompt, simply press Enter. In the image above, it has been edited out because of some typo mistake. You can change your test command from the eventually forming package.json file as well.
- In the git repository prompt, you can fill the URL of the git repository where the package will be hosted.
- Fill in the keywords, author, and license or you can press ‘Enter’ your way through them. These can be later modified in the package.json.
- Add “type”: “module” in the package.json file in order to use the latest import/export ES6 feature.
- Include a README.md file in the project for potential downloaders to see. This will appear on the homepage of your module. Note that, the file should be a markdown. A README.md should be added to an npm module so that potential users for the purposes of serving them with information like module description, how to use the package, how to contribute to package, etc.
Ultimately, it is desirable if our project directory looks something like this:
3. Building a module: This phase is the coding phase. If you have any experience in using NPM modules, you would know that NPM modules expose methods that are then used by the project. A typical control flow is:
Let’s first implement a simple function that adds two numbers in the npm module. This function looks like the below:
File Name: index.js
javascript
export const gfgFns = { add : function addTwoNums (num1, num2 ) { return (num1 + num2) ; } } |
Note that, the structure of the index.js file (which is the entry point of the npm module that we are building).
- const gfgFns = {} The object that is exported for others to use.
- add: function addTwoNums() The function name (addTwoNums) is marked by ‘add’. This ‘add’ name is used to call this function to add two numbers.
- module.exports = gfgFns The gfgFns object is then exported with this name. When this function needs to be used in some other file.
4. Publishing a module: After completion of the coding module, publish the npm package. To publish the package, there is one thing to keep in mind- if your package name already exists in the npm registry, you won’t be able to publish your package. To check if your package name is usable or not, go to the command line and type
npm search packagename
If your package name is usable, it should show something like the image below.
If your module name already exists, go to the package.json file of the npm module project and change the module name to something else.
Now after checking the name availability, go to command-line/terminal and do the following:
npm publish
Now, let’s try to use this module and see if it works.
- Make a fresh project directory.
- In the terminal, type npm init to initialize the Node project.
- Now do npm install gfgnpmpkgupload to download the npm module that we just made.
- Now everything is set, let’s try to run the node.js file and see if our module is correctly uploaded, published, imported in our new project, and used.
5. Updating and managing versions: If a software is being developed, it is obvious that it has versions. Versions are a result of bug fixes, minor improvements, major improvements, and major releases. To cater to versioning, NPM provides us with the following functionality.
Versioning and publishing code: NPM allows us to version our module on the basis of semantic-versioning. There are three types of version bumps that we can do, ie, patch, minor, and major. For example, if the current module version is 0.4.5:
# note how minor version upgrade resets patch version to 0, similarly, # major version upgrade sets minor and patch #to 0. > npm version patch # update version to 0.4.6 > npm version minor # update version to 0.5.0 > npm version major # update version to 1.0.0
When we run the above command, the version number in the package.json file is automatically updated as well.
Note: If the module is being re-published without bumping up the version, the NPM command line will throw an error. For example, look at the below image.
Here, the command line threw an error because an ‘npm publish’ was attempted without bumping up the version.
An obvious note: You can’t bump down the version. For example, the version can’t change from 0.1.2 to 0.1.1.
What happens when the user has an older version of the module? When an npm module is re-published (updated), the users just have to run ‘npm install gfgnpmpkgupload’ (npm install <packagename>) again to get the latest version.
A package dependent on other packages: In the journey of developing packages, it is common to search, use, and see dependencies. Doing this takes place like something below:
- In the npm module project, install the dependencies that are required by your npm module.
- Install those dependencies to your project using
npm install packagename1[ packagename2]
- Check that these dependencies are now mentioned in the ‘dependencies’ key in the package.json file. Note that the dependencies and their version mentioned here will be carried on forward with the npm package.
- After assuring that all the above steps are rightly executed, simply publish the module using
> npm version minor npm publish
- The above procedure should execute successfully, and the result should be available to see in the npm registry website like below:
Building a more complex module: Let’s try to build a module that reads a txt file, extracts numbers from the file, adds them all, and display the result in a console. To do this, our npm module should be this.
Now, that we have our module set, let’s import it into our new project using
npm install gfgnpmpkgupload
Before running the above command, run
npm init -y
to set up the project.
Make your project file structure like below:
The datafiles should contain a numFile.txt that has the numbers that have to be added and displayed in the console.
// numFile.txt - sum = 55 1 2 3 4 5 6 7 8 9 10
To consume this numFile.txt, we will have a gfgapp.js that will do the actual addition.
To test this, go to command-line and run
node gfgapp.js
NPM module boilerplate: NPM module boilerplates are also available for project scaffolding on yeoman.io . Various combinations of technologies are available and you can use the generator that you like. To start, go to Yeoman Generator Search and search for something like ‘npm module boilerplate’.
Unpublishing an NPM package: An NPM package should be taken down within 72 hours of the initial publish. The other way is to contact the npm registry. If you are unpublishing within 72 hours, use the following command:
npm unpublish packageName
NPM’s unpublishing packages from the registry is a good page to go through to learn more about this.
Example: Use the published package to add two numbers.
Filename: app.js
JavaScript
import GFGFns from 'gfgnpmpkgupload' ; console.log(GFGFns.add(4, 5)); |
Output: