Automate publishing npm packages

Wilson Tan
2 min readOct 29, 2020

The developer team in your organization has made some changes and it’s time to build and publish the npm package to the registry by executing npm publish. Although it’s not a heavy task, we can possibly automate this process so that we can take some workload off the shoulders of the developer team, leaving them to focus on what they do best!

Now, here’s what we can do. By using tools like Jenkins, Travis CI, CircleCI etc, we can publish the npm package to registry automatically upon changes made on the code in the repository.

However, we will get an error when we are trying publish a package with the same package name and version. Therefore, we need to implement some validation before we publish it.

Let’s dive into the bash code which we can put into our CICD tool to automate the publishing process.

npm run buildVERSIONS=$(npm view <package_name> versions --json)CURRENT_VERSION=$(node -pe "require('./package.json').version")if [[ ! " ${VERSIONS[@]} " =~ $CURRENT_VERSION ]]; then
npm publish
fi

Prerequisite:

  • Ensure that you can run npm command in your CICD environment.

Steps:

  1. First, build the package by running npm run build
  2. Get all the published versions of the package npm view <package_name> versions --json and store it into variable VERSIONS
  3. Get the current version of the package which is stored in package.json file and store it into variable CURRENT_VERSION.
  4. Implement validation to check if the current version exists in the list of published versions [[ ! “ ${VERSIONS[@]} “ =~ $CURRENT_VERSION ]]. If it doesn’t, then we will publish the package by executing npm publish. By having this logic, we can then notify the developer team to update the package version when they want to publish it to the registry.

Cheers!

--

--