在.gcloudignore 中允许node_modules 不再有效。
自 2020 年 10 月/11 月起,App Engine 部署为 switched to buildpacks。由此触发的 Cloud Build 步骤将始终删除上传的 node_modules 文件夹并使用 yarn 或 npm 重新安装依赖项。
以下是相关的 buildpack 代码:
https://github.com/GoogleCloudPlatform/buildpacks/blob/89f4a6ba669437a47b482f4928f974d8b3ee666d/cmd/nodejs/yarn/main.go#L60
这是一种理想的行为,因为上传的 node_modules 可能来自不同的平台,并且可能会破坏与用于在 App Engine 环境中运行您的应用的 Linux 运行程序的兼容性。
因此,为了在 Cloud Build 中跳过 npm/yarn 依赖项安装,我建议:
-
将 Linux runner CI 与您在 App Engine 环境中使用的相同 Node 版本使用。
-
使用您的 node_modules 创建 tar 存档,不要在每个 gcloud app deploy 上上传大量文件。
-
在.gcloudignore 中忽略node_modules 目录。
-
在preinstall 脚本中解压缩node_modules.tar.gz 存档。不要忘记保持向后兼容性以防 tar 存档丢失(本地开发等):
{
"scripts": {
"preinstall": "test -f node_modules.tar.gz && tar -xzf node_modules.tar.gz && rm -f node_modules.tar.gz || true"
}
}
注意... || true 的事情。这将确保 preinstall 脚本无论如何返回零退出代码,并且 yarn/npm install 将继续。
为 App Engine 部署打包和上传依赖项的 Github Actions 工作流程可能如下所示:
deploy-gae:
name: App Engine Deployment
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
# Preferable to use the same version as in GAE environment
- name: Set Node.js version
uses: actions/setup-node@v2
with:
node-version: '14.15.4'
- name: Save prod dependencies for GAE upload
run: |
yarn install --production=true --frozen-lockfile --non-interactive
tar -czf node_modules.tar.gz node_modules
ls -lah node_modules.tar.gz | awk '{print $5,$9}'
- name: Deploy
run: |
gcloud --quiet app deploy app.yaml --no-promote --version "${GITHUB_ACTOR//[\[\]]/}-${GITHUB_SHA:0:7}"
这只是initially suggested hack 的扩展版本。
注意:如果您的 package.json 中有 gcp-build 脚本,您将需要创建两个存档(一个用于生产依赖项,一个用于开发)并修改预安装脚本以解压缩当前需要的一个(取决于NODE_ENV 由 buildpack 设置)。