教程-如何用travis-ci实现自动化部署前端项目

1,861 阅读2分钟

背景:UI组件库做好了,但是要将UI文档自动发布,之前都是每次提交代码的时候去手动构建后再发布文档,但是这样太麻烦,所以想用travis-ci自动化构建一个VUE UI框架的官方文档。组件库源码地址 github.com/ninecat-ui/…

实现的方法

  • 在项目里面建一个docs文件夹,然后commit后再构建文档,然后push到原代码仓库,通过gh-page关联docs文件实现官方文档的预览。

  • 官方文档为另外的项目,以 **ninecat-ui.github.io**这种主页名命名项目,然后commit后构建文档,再clone项目=》commit项目=》提交项目。

两种方法原理都可行,但是第一种方式会发现在travis-ci第二次提交的时候,git的记录是没有的,所以放弃了第一种,然后用第二种方法实现的,第二种方法有个好处就是不用担心你的操作会影响到原项目,因为没有push操作,所以下面就讲解一下第二种方法实现的步骤。

实现步骤

1.Github 账号关联 TravisCI

用 Github 账号登录travis-ci.com/,你的所有 Repo 都会列出来,选择激活你想要 build 的 Repo,这一步基本都是傻瓜操作,很简单,无需赘述。

2.配置环境变量

环境变量有两种,一种是配置在.travis.yml文件里面的,

.travis.yml文件

另一种是配置在travis-ci的后台系统中进行,在setting里的Environment Variables里面。

travis-ci后台配置

第二种方式的环境变量主要是用于第三方系统的权限校验,当然再本次实践中也需要进行配置,配置一个github的token以便后面的提交操作。

按照下面的步骤配置GitHub的token (1)进入GitHub的个人设置,Settings=> Developer settings=>Personal access tokens=>Generate new token 进行如下勾选就行

Generate new token
(2)进入travis-ci的后台系统中配置环境变量Environment Variables如travis-ci后台配置图所示,新增一个环境变量,然后将GitHub建立的token填入其中。DISPLAY VALUE IN BUILD LOG 选项不要勾选,否则环境变量会在你执行build脚本的时候显示出来。

3.配置脚本构建


# Designated language. https://docs.travis-ci.com/user/languages/javascript-with-nodejs/
language: node_js

# Environment variables
env:
  global:
    - GitHub_REF: github.com/ninecat-ui/ninecat-ui.github.io.git

# Install dependence
install:
  - npm install
  - npm install -g codecov

# Cache the node_modules folder and don't need to download and install all npm packages every time.
cache:
  directories:
    - node_modules
# Specify the node version.
node_js:
  - "11.1.0"
# Perform builds only on the specified branch.  https://docs.travis-ci.com/user/customizing-the-build/#building-specific-branches
branches:
  only:
    - master
# The script to execute.
script:
  - npm test
  - codecov
  - npm run docs:build
  - cd docs
  - git init
  - git add -A
  - git commit -m "docs:update docs"
  - git push --force --quiet "https://${GitHub_TOKEN}@${GitHub_REF}" master:master
# Configure to send notifications when the build fails. https://docs.travis-ci.com/user/notifications
notifications:
  webhooks:
    urls:
      - https://www.travisbuddy.com/
    on_success: never # Successful build does not send mail.
    on_failure: always # Build failure always sends a message.

上面的脚本可以根据官方文档docs.travis-ci.com/user/speedi…自行定义和使用