Rico Suter's blog.
 

For some open-source projects I need to publish NPM packages during the CI release on AppVeyor. Unlike with NuGet packages, you have to do that manually by installing NodeJS and NPM, creating an .npmrc file with your NPM credentials and publishing the package. This blog post describes this procedure in detail.

Retrieve auth token

To authenticate with the npmjs.org NPM feed, you have to manually retrieve the npmjs.org auth token. To do so, you have to first login to NPM via CLI:

npm login

This command creates or updates the .npmrc file in your local user directory (‪C:\Users\MyUser\.npmrc). The file content looks like:

//registry.npmjs.org/:_authToken=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

Copy the auth token in the form of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx. It will be used in the next step.

Configure AppVeyor to publish an NPM package

In the AppVeyor web UI, under Settings / Environment, add the following two environment variables:

  • npm_auth_token: The previously retrieved auth token (in the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
  • nodejs_version: The NodeJS version to install (e.g. 8)

Then add the following code as PowerShell install script:

Install-Product node $env:nodejs_version
npm install --loglevel=error

"//registry.npmjs.org/:_authToken=$env:npm_auth_token`n" | out-file "$env:userprofile\.npmrc" -Encoding ASCII

This script installs NodeJS and NPM. Next, it creates the .npmrc file on the AppVeyor CI server.

In the Settings / Deployment settings, you can now publish your NPM package in the after deployment script (after_deploy):

npm publish "src/MyNpmPackage"

The appveyor.yml file

Instead of manually configuring the CI build, you can also use an appveyor.yml file. This shows the relevant parts to enable NPM publish:

environment:
  nodejs_version: 6
install:
- ps: >-
    Install-Product node $env:nodejs_version
    npm install --loglevel=error

    "//registry.npmjs.org/:_authToken=$env:npm_auth_token`n" | out-file "$env:userprofile\.npmrc" -Encoding ASCII
after_deploy:
- ps: npm publish "src/Dnt.Npm"

Important: Never put secrets in public files (e.g. on GitHub) - in our case, define the npm_auth_token environment variable on AppVeyor.com.



Discussion