前导

  1. 假设你已经有了一个gitlab的项目,且项目中有一个package.json文件
  2. 假设你已经有了一个gitlab的runner,且已经注册到了gitlab中
  3. 假设你已经安装了nodejs
  4. 假设你node项目的打包命令为 npm run build
  5. 假设你node项目打包生成的目录为 dist
  6. 假设你gitlab-runner的运行模式为docker

项目配置

  1. 在项目根目录中新建一个 .gitlab-ci.yml 文件
  2. 假设项目有多个分支版本,分别为 test dev prod

ci stage 推断

  1. 寻找项目是否存在需要全局install的npm包
    • 如果存在,那么需要在ci的before_script中添加全局install的命令
  2. 项目是否需要特殊的npm源
    • 如果需要,那么需要在ci的before_script中添加npm源的命令
  3. 项目是否需要特殊的npm版本
    • 如果需要,那么需要指定映入的image为特殊的npm版本
  4. 总结
    1. 将stage划分为 prepare config build 等阶段(当然,简单项目可以直接放一起,分开是为了大项目的可读性)
    2. prepare阶段用于构建全局的npm包,以及配置npm源
    3. install阶段用于安装项目的依赖
    4. build阶段用于构建项目
    5. 项目的build需要多个job,对应多个环境版本

ci 编写

  1. 各阶段合并的写法
    stages:
    - build
    .build:
    stage: build
    before_script:
    #假设全局安装了cnpm
    - npm install -g cnpm --registry=https://registry.npm.taobao.org
    #假设项目需要使用淘宝源
    - npm config set registry https://registry.npm.taobao.org
    script:
    - npm install
    - npm run build:$CI_COMMIT_REF_NAME
    artifacts:
    paths:
    - dist/

    build-test:
    <<: *build
    only:
    # 只有test分支的提交才会触发
    - test
    build-dev:
    <<: *build
    only:
    # 只有dev分支的提交才会触发
    - dev
    build-prod:
    <<: *build
    only:
    # 只有prod分支的提交才会触发
    - prod
  2. 分离job写法,简单项目不推荐这种写法
    cache:
    paths:
    - node_modules
    - dist
    stages:
    - prepare
    - config
    - build
    pre:
    stage: prepare
    script:
    - npm config set registry https://registry.npm.taobao.org

    conf:
    needs: [pre]
    stage: config
    script:
    - npm config set registry https://registry.npm.taobao.org

    .build:
    stage: build
    needs: [conf]
    script:
    - npm install
    - npm run build:$CI_COMMIT_REF_NAME
    artifacts:
    paths:
    - dist/

    build-test:
    <<: *build
    only:
    # 只有test分支的提交才会触发
    - test
    build-dev:
    <<: *build
    only:
    # 只有dev分支的提交才会触发
    - dev
    build-prod:
    <<: *build
    only:
    # 只有prod分支的提交才会触发
    - prod