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

Issue

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...

Solution

Just use the only:changes flag doc

The job will be:

install_packages:
  stage: install
  script:
    - npm prune
    - npm install
  cache:
    key: ${CI_COMMIT_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/

Answered By – jwillker

Answer Checked By – Dawn Plyler (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published