如何在GitHub Actions中缓存yarn包

问题描述:

我正在使用GitHub Actions构建我的TypeScript项目. 每次我执行操作时,我都在等待3分钟以安装所有依赖项.

I am using GitHub Actions to build my TypeScript project. Everytime I run action I am waiting 3 minutes for all dependencies to get installed.

是否可以缓存纱线依赖项,因此构建时间会更快?

Is there way to cache yarn dependencies, so build time will be faster?

我尝试过:

     - name: Get yarn cache directory path
       id: yarn-cache-dir-path
       run: echo "::set-output name=dir::$(yarn cache dir)"

     - uses: actions/cache@v1
       id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
       with:
         path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
         key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
         restore-keys: |
           ${{ runner.os }}-yarn-

    - name: Install yarn
      run: npm install -g yarn

    - name: Install project dependencies
      run: yarn

但是构建时间仍然相同.

but build time is still same.

如缓存步骤id字段旁边的注释中所述:

As mentioned in the comment next to the id field for the caching step:

使用它来检查cache-hit(steps.yarn-cache.outputs.cache-hit != 'true')

您缺少确定是否应运行该步骤的条件if属性:

You're missing a conditional if property that determines whether the step should be run:

- name: Install yarn
  run: npm install -g yarn

- name: Install project dependencies
  if: steps.yarn-cache.outputs.cache-hit != 'true' # Over here!
  run: yarn

P.S.您可能应该使用设置NodeJS GitHub Action,它还为您设置了Yarn:

P.S. You should probably use the Setup NodeJS GitHub Action that additionally sets up Yarn for you:

- uses: actions/setup-node@v1
  with:
    node-version: '10.x' # The version spec of the version to use.

有关完整列表,请参见 action.yml文件有效输入.

See the action.yml file for a full list of valid inputs.

事实证明,纱线包含在安装在GitHub托管的Ubuntu 18.04.4 LTS(ubuntu-latest/ubuntu-18.04)运行器上的软件,因此无需包括全局安装Yarn的步骤.

As it turns out, Yarn is included in the list of software installed on the GitHub-hosted Ubuntu 18.04.4 LTS (ubuntu-latest/ubuntu-18.04) runner, so there's no need to include a step to globally install Yarn.