deploy-npm-package-with-travis


方法一: 利用travis內置的deploy provider

# Login the travis.com
travis login --com

# encrypt the API_KEY for travis API
travis encrypt [NPM_API_KEY] --com --add 'deploy.api_key'

這個命令會在.travis-ci.yaml中加入一個deploy的secret 若果是公開的repo最好把它抽出來以環境變數的形式去載入

但這個如果用環境變數的話不知為何總是跑出401 Unauthorized you must be logged in to publish packages travis

搞了一輪之後決定用第二個方法

方法二: deploy script及利用.npmrc

新增一個deploy.sh

echo "//registry.npmjs.org/:_authToken=${NPM_API_TOKEN}" > $HOME/.npmrc

npm publish

這會將環境變數寫成npmrc 而npm script會利用它來認證並發佈

檔案如下

language: node_js
node_js:
- '11'
- '10'
- '8'
stages:
- test
- name: deploy
  if: branch = master
cache: npm
# Use script instead of npm provider as it cannot auth via env variables?
deploy:
  provider: script
  script: "./deploy.sh"
  skip_cleanup: true
  # only on tagged builds
  on:
    tags: true
# Send an email when a new version is released
notifications:
  email:
    recipients:
    - "$NPM_EMAIL"
    on_success: change
    on_failure: always

參考