Deploy angular app to Github Page by Travis CI

Reading Time: 2 minutes

Loading

1) Install npm dependencies

angular-cli-ghpages is a plugin that pushes angular application to gh-pages branch.

npm install angular-cli-ghpages --save-dev 

Add prettier schematic to Angular project

npm install -g @schuchard/prettier
ng g @schuchard/prettier:add

2) Create a .travis.yml file that details the deployment steps

3) Specify language is node_js and node version is 8

language: node_js
node_js:
    - '8'

4) Cache npm dependencies and production build directory, dist.

cache:
    npm: true
    directories:
        - node_modules
        - dist/

5) Create environment variables to store github organization, repo name, github username and github email respectively. GH_TOKEN is your secret github token that is saved under Settings of your repository. You can find the link to generate github token here

env:
    global:
        - GITHUB_ORG="https://GH_TOKEN@github.com"
        - REPO_NAME="<repository name>"
        - GITHUB_NAME="<username>"
        - GITHUB_EMAIL="<email address>"

6) Add “before_script” to install npm dependencies without modifying package-lock.json file

before_script:
    - npm install --no-save

7) Add “script” to run different tasks before the final deployment

script:
    - npm audit
    - npm run prettier
    - npm run lint
    - npm run test-headless
    - npm run build-ngh

branches:
    only:
        - master

8) The above tasks are created in scripts of package.json:

  • npm audit audits npm dependencies to ensure vulnerabilities do not exist
  • npm run prettier formats files with Prettier code formatter
  • npm run lint performs linting on source files to identify any lint problem and aborts the process prematurely
  • npm run test-headless executes test cases in headless Chrome browser and terminates if any test case fails
  • npm run build-ngh compiles the source codes on master branch to production build and places the artifacts to dist/<project> directory
"scripts": {
    "prettier": "prettier --write \"**/*.{js,json,scss,ts}\"",
    "lint": "ng lint",
    "build-ngh": "ng build --prod --base-href \"https://railsstudent.github.io/<repository name>/\"",
    "test-headless": "ng test --watch=false --browsers=ChromeHeadless"
  }

9) If all script tasks finishes successfully, the task in “after_success” is executed to push the static pages to gh_pages branch

after_success:
    - ngh --repo="$GITHUB_ORG/$GITHUB_NAME/$REPO_NAME.git" --name="$GITHUB_NAME" --email="$GITHUB_EMAIL" --dir=dist/ng-rxjs-state-management-demo --no-silent

10) Add notifications configuration to receive notification email when travis build fails

notifications:
email:
recipients:
- somebody@example.come
on_success: never # default: change
on_failure: always # default: always

11) Navigate to https://<username>.github.io/<repo name>/ to view the static pages