Automate publishing npm packages
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:
- First, build the package by running
npm run build
- Get all the published versions of the package
npm view <package_name> versions --json
and store it into variableVERSIONS
- Get the current version of the package which is stored in
package.json
file and store it into variableCURRENT_VERSION
. - 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 executingnpm 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!