Node js create a local module and include it in package.json
Here is a step by step guide for creating a custom local module in a node.js project. The local module will be used like any other published libraries that are installed as dependencies in the package json file. One of the benefits of doing this is that it will no longer need to specify the full file path for the module, and it can be imported anywhere in the project without having to specify the full file path.
1. At the root folder of the node js project, create a folder math-utils and then create an index.js file with the following.
exports.add = (a, b) => a + b; exports.subtract = (a, b) => a - b; exports.multiply = (a, b) => a * b; exports.divide = (a, b) => a / b;
2. cd into the math-utils folder, and run this command to initialize the module, when prompted for module name, description, versions, license, etc, just press enter or type anything that make sense to the module and then enter.
npm init
3. cd.. back to the parent folder, the project root folder, then run the following command to include the module to the project’s package json. What it does is to add a dependency to the project package json to include this custom local module math-utils, and it will also create the math-utils inside the node_modules folder where all the installed modules are.
npm install --save math-utils
4. The included math-utils module will look like this in the package.json file.
"dependencies": { "math-utils": "file:math-utils", }
5. Use the custom local module anywhere in the project just like any other modules that are downloaded from the npm repository.
const { add, subtract, multiply, divide } = require('math-utils'); console.log(`10 + 1 = ${add(10, 1)}`); console.log(`10 - 1 = ${subtract(10, 1)}`); console.log(`10 * 2 = ${multiply(10, 2)}`); console.log(`10 / 2 = ${divide(10, 2)}`);
Search within Codexpedia
Search the entire web