Creating your own NPM modules
NPM modules or we can say NPM packages are a very vital part of any Node.js based project. In this article, we’ll practically learn how to create and publish the NPM packages.
To build, we need to follow below steps:
1. Open the terminal and use these commands
2. Now initialize a Node.js project and follow the instructions
After you provide the above information, a new file package.json will be created in your package directory.
3. Now create a file named index.js. This file is the entry point for your package, the same you mentioned in the above point while initializing your project. Define a function as a property of the
exports object. Enter the following lines in your index.js and save your changes.
Above, you have created your NPM package, which will print the current date. Now you need to create an account on npmjs.com. Open the terminal again and switch to your package directory.
After login, you need to run the following command in your project directory.
Make sure you will choose a unique name for your package; otherwise, you will get an error while publishing your package.
If you have noticed, we have used “— access public” in our command. This will publish the package as a public scope. You can also publish with a private scope, but that service is paid. For any organization, you need to have paid service if you want to keep your packages as private scope.
Let’s install your newly published package and use it. Create a new Node.js project and run the following command.
In your app.js or index.js for your new project use your package as follows:
You are now ready to create your own NPM packages. You can modify your packages according to your business requirements and publish the same.