NPM 缓存步骤在 Azure DevOps 中不起作用

sam*_*sam 13 android caching azure node.js npm

我按照 Microsoft 的以下文档为我尝试在 azure 中构建的 Android 应用程序配置 npm 缓存步骤,我使用的是 package.json,而不是 package.json-Lock。

https://learn.microsoft.com/en-us/azure/devops/pipelines/release/caching?view=azure-devops#nodejsnpm

我能够在缓存后步骤中上传缓存依赖文件,并在第二次运行管道时在开始时正确上传该文件,但即使在工作区中下载 npm 缓存数据后,npm 安装步骤仍然调用远程库并下载远程依赖项。

我还尝试为 npm install 步骤运行npm install --prefer-offline但确实有效。如果我还缺少任何内容,请告诉我。

谢谢。

Chr*_*ers 14

使用该Cache任务来缓存应用程序的node_modules 文件夹。使用缓存命中变量(cacheHitVar)来存储缓存恢复的结果。true当缓存恢复(缓存命中)时它将被设置为,否则设置为false

然后为安装依赖项的任务使用一个条件(例如npm ci)。仅在缓存未命中时安装它们。

steps:
  - task: Cache@2
    displayName: Cache node_modules
    inputs:
      key: 'npm | "$(Agent.OS)" | $(Build.SourcesDirectory)/package-lock.json'
      path: $(Build.SourcesDirectory)/node_modules
      cacheHitVar: CACHE_RESTORED

  - task: Npm@1
    displayName: 'Install the dependencies'
    inputs:
      command: custom
      verbose: false
      customCommand: 'ci'
    condition: ne(variables.CACHE_RESTORED, 'true')
Run Code Online (Sandbox Code Playgroud)

当缓存成功恢复后,您将在管道执行中看到以下输出。

Azure 管道执行


Ned*_*udi 5

请查看 Microsoft 关于节点模块缓存的以下官方建议https://learn.microsoft.com/en-us/azure/devops/pipelines/release/caching?view=azure-devops#nodejsnpm

variables:
  npm_config_cache: $(Pipeline.Workspace)/.npm

steps:
- task: Cache@2
  inputs:
    key: 'npm | "$(Agent.OS)" | package-lock.json'
    restoreKeys: |
       npm | "$(Agent.OS)"
    path: $(npm_config_cache)
  displayName: Cache npm

- script: npm ci

Run Code Online (Sandbox Code Playgroud)

由于 npm ci 会删除 node_modules 文件夹以确保使用一致、可重复的模块集,因此在调用 npm ci 时应避免缓存 node_modules


som*_*men 1

这不是一个答案,因为我有完全相同的问题,但这是我的设置。

- task: Cache@2
  displayName: Cache npm
  inputs:
    key: 'npm | "$(Agent.OS)" | $(Build.SourcesDirectory)/XX/package-lock.json'
    restoreKeys: |
       npm | "$(Agent.OS)"
    path: $(npm_config_cache)

- task: Npm@1
  displayName: Npm restore dependencies
  inputs:
    command: 'custom'
    workingDir: '$(clientapps)'
    customCommand: 'install --cache $(npm_config_cache)'
Run Code Online (Sandbox Code Playgroud)

添加--cache将 npm 的缓存文件设置到特定位置。我现在正在使用 --prefer-offline 运行构建,看看是否有帮助。如果有帮助的话我会在这里回答。