May 24, 2022

Publish a npm package and work with it locally

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.

Publish the package

  1. 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.
  2. Open your terminal, run npm login and enter your username, password and email.
  3. In 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"
    }
    }
    
  4. In your module folder run npm publish,

  5. You’ll find the new module in the packages section of your npmjs.com account. We are ready to npm install everything!! Wait.. wait..

Npm lemmings

To publish a new version, just make sure to update the module version number in your package.json and run npm publish again.

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 most likely be using your package within a project, but it is not convenient to work in a node_modules folder, you would risk losing your work every time you update the npm dependencies. Let’s make things easier:

  1. Clone your module in any convenient location inside the project.
  2. Enter in your module folder with the terminal and run npm link.
  3. In the project root run npm link @nuovecode/npm-package

Now you’ll have in node modules a symlinked version of your module and you can safely work in the location you prefer.

If you get a 403 Error

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.

Ah! Speaking of publishing something at all costs, I haven’t forgotten my little gem for you.

Jack Lemmon and Walter Matthau in The Front Page, Billy Wilder 1974

No copyright / do whatever the hell you want with these contents
Built with Hugo and Kiss theme. Hosted on Netlify. Icons made by Ddara