Assume You are developing an npm module and you want to test it before publishing it to the npm registry. Npm provides a way to test your module locally before publishing it to the npm registry.
In this post, I will show you how to test npm
modules before publishing it to npm registry
Let’s first create a module for converting string to title case.
Run the following command
npm init -y
touch index.js
After running the above command your folder structure will look like below
Open your project in VS Code
and then edit the index.js
file
module.exports=function(str){
return str[0].toUpperCase()+str.slice(1);
}
How to test the module locally
To test the module locally we will use npm link
the command which creates a symbolic link.
To create a link run the following command
cd titlecase
npm link
if the command run successfully you will see the following output
C:\Users\lenovo\AppData\Roaming\npm\node_modules\titlecase -> F:\blog\modules\titlecase
How to use
To use the above module in your main project. Follow the following steps
-
Navigate to your main project
-
Run the following command in the terminal (make sure you are inside the project)
npm link titlecase
if the command run successfully you will see the output as below
F:\blog\modules\module-demo\node_modules\titlecase -> C:\Users\lenovo\AppData\Roaming\npm\node_modules\titlecase -> F:\blog\modules\titlecase
Now you can use the module as below
const titleCase=require('titlecase');
console.log(titleCase("hello"));