Npm packages are extremely useful for creating reusable pieces of code or for sharing your work with other developers.
In this post I’ll explain how to create one in minutes and work on it within a project.
In This Article:
Publish the package
- Create an account on npmjs.com if you don’t already have one. Make sure to verify your email otherwise you’ll have an error when publishing.
- Open your terminal, run
npm login
and enter your username, password and email. - In the root of your module make sure to have a valid
package.json
.
{
"name": "@nuovecode/npm-package",
"version": "1.0.0",
"description": "A clear description of what this package does",
"repository": "url of the repository if any",
"license": "MIT",
"main": "index.js",
"publishConfig": {
"access": "public"
}
}
- In the same folder you can just run
npm publish
, - You’ll find the new module in the packages section of your npmjs.com account.
Work on the package locally
Now that you have your first package released, you may want to work on it or add new features.
You will use your package within a project,
but you can’t just work in the node_modules
folder, you would risk losing your work every time you update the npm dependencies.
Let’s make things easier:
- Clone your module in any convenient location inside the project root.
- In your module folder (the one you just cloned) run
npm link
. - In the project root run
npm link @nuovecode/npm-package
Now you’ll have in node_modules a symlinked version of your module.
You will work in the folder you cloned, and you will see your changes in real time because it’s symlinked with the module within node_modules. Nothing will be lost because your original module will not be overwritten by npm install.
Publish a new version of the package
- To publish a new version update the module version number in your
package.json
, for example from1.0.0
to2.0.0
{
"name": "@nuovecode/npm-package",
"version": "2.0.0",
..
}
}
- Run
npm publish
again. - Now in your npm account you will find your module updated to the latest version
Error: 403 Forbidden - You do not have permission to publish “qdb”
Sometimes you may get this error on npm publish
403 Forbidden - PUT https://registry.npmjs.org/qdb -
You do not have permission to publish "qdb". Are you logged in as the correct user?
Possible causes can be:
- Missing login. Run
npm login
again and make sure there are no error in console. - You didn’t verify your email. You should see a notice in your npm account.
- The package name is taken already. Change it, be creative.
Speaking of publishing something at all costs, will Walter Matthau be able to publish his article before everyone else? Watch this wonderful movie to find out.
Jack Lemmon and Walter Matthau in The Front Page, Billy Wilder 1974