Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only 'npm install' in GitLab CI when package.json has been updated

I'm using GitLab CI for a project and the first step of the process is npm install. I cache node_modules for quicker runs of the same job later on, and also define them as build artifacts in order to use them in later stages. However, even though I cache node_modules and it's up-to-date, calling npm install each time the install_packages job is run takes a long time, since the command goes through all of package.json and checks for updates of packages and such (I assume).

Is there any way to only run npm install in the install_packages job depending on some condition? More specifically (what I think would be the best solution), whether or not package.json has been changed since last build?

Below is the relevant part of my .gitlab-ci.yml file:

image: node:6.9.1

stages:
  - install
  - prepare
  - deploy

install_packages:
  stage: install
  script:
    - npm prune
    - npm install
  cache:
    key: ${CI_BUILD_REF_NAME}
    paths:
      - node_modules/
  artifacts:
    paths:
      - node_modules/
  only:
    - master
    - develop

build_and_test:
  stage: prepare
  script:
    #do_stuff...

deploy_production:
  stage: deploy
  #do_stuff...

deploy_staging:
  stage: deploy
  #do_stuff...
like image 736
jorundur Avatar asked Nov 15 '16 16:11

jorundur


People also ask

Why use npm ci instead of npm install?

Use npm install to install new dependencies , or to update existing dependencies (e.g. going from version 1 to version 2). Use npm ci when running in continuous integration, or if you want to install dependencies without modifying the package-lock.

Does npm install automatically add to json?

json, you can re-run npm init -y and the repository field will be added automatically to your package. json.

Does npm ci require package json?

The main differences between using npm install and npm ci are: The project must have an existing package-lock. json or npm-shrinkwrap. json .

Does npm install update package json?

The npm install installs all modules that are listed on package. json file and their dependencies. npm update updates all packages in the node_modules directory and their dependencies.


1 Answers

Just use the only:changes flag doc

The job will be:

install_packages:
  stage: install
  script:
    - npm prune
    - npm install
  cache:
    key: ${CI_BUILD_REF_NAME}
    paths:
      - node_modules/
  artifacts:
    paths:
      - node_modules/
  only:
    refs:
      - master
      - develop
    changes:
      - package.json

Another point is: You set the cache the right way? Read this: https://docs.gitlab.com/runner/configuration/autoscale.html#distributed-runners-caching https://docs.gitlab.com/ee/ci/caching/

like image 140
jwillker Avatar answered Sep 21 '22 14:09

jwillker