How to publish an NPM package in AppVeyor

June 17, 2018, (updated on July 14, 2018), Software Development

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.


Tags: , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

This site uses Akismet to reduce spam. Learn how your comment data is processed.