使用 tsconfig.json 扩展父 tsconfig.json

问题描述 投票:0回答:1

我曾经使用 CI 工具部署我的 Google Cloud Functions

gcloud functions deploy testFunction --region europe-west1 --trigger-http --runtime nodejs16 --source ./testFunction --set-env-vars ...
我的目录结构如下(只显示必要的文件):

.
├── testFunction
│   ├── package.json
│   ├── src
│   │   └── index.ts
│   └── tsconfig.json
└── tsconfig.json

我的问题

大约 2 天以来,我的 Google Cloud Function 在 Google Cloud Build 中构建时出现错误。问题是找不到根目录中的 tsconfig.json。当我尝试下载已上传到 Google 的源代码时,我可以看到只有 testFunction 目录正在上传。有趣的是,它以前也是这样并且有效。所以我假设由于某种原因谷歌过去忽略了 tsconfig.json ?

文件

testFunction/tsconfig.json
从根文件夹扩展父
/tsconfig.json

// /testFunction/tsconfig.json
{
  "extends": "../tsconfig.json",
  "include": ["./src"],
  "compilerOptions": {
    "outDir": "./build",
    "rootDir": "./src",
    "tsBuildInfoFile": "buildcache.tsbuildinfo"
  }
}

我尝试过的事情/临时解决方案

目前我找到了两个临时解决方案:

  1. 复制父 tsconfig.json 的内容并且不扩展父 tsconfig.json
  2. ln -s
    做一个别名并将父
    tsconfig.json
    链接为
    parent.tsconfig.json
    并扩展那个。

这两种解决方案似乎都不是很优雅,我想知道为什么这种变化突然发生,以及是否有更好的解决方案(比如在部署/构建期间解析父 tsconfig.json 或以某种方式将其包含在构建中)。

任何帮助将不胜感激,谢谢!

typescript google-cloud-platform google-cloud-functions tsconfig
1个回答
0
投票

让我们检查一下用于部署函数的命令,同时仅查看问题的相关部分:

gcloud functions deploy testFunction --source ./testFunction

这告诉

gcloud
应用程序获取目录
./testFunction
及其内容并将它们发送到 Cloud Build。重要的是要注意它只会发送only那个目录及其内容;它们成为 Cloud Build 的 build context,就像 Docker build context 一样。

我不能说这在过去为什么或如何对你有用。我假设您误解了早期部署中发生的事情或配置更改,因为我用

gcloud functions deploy
描述的构建上下文一直是正确的。

符号链接也会有问题,因为如果您在

./testFunction
中有一个指向
../tsconfig.json
的符号链接,那么当 Cloud Build 解压缩构建上下文时,它将指向父目录中不存在的文件。例如,如果它解包到
/app
,它将在解包的容器内寻找
/tsconfig.json
,但找不到它。

了解构建上下文在部署 Cloud Functions 时很重要。看起来你有一个 monorepo,我认为你有不止这个功能。请记住,如果您告诉它使用

.
作为
--source
(或者如果您省略
--source
),那么它将发送整个目录结构作为构建上下文。这可能不是您想要的,因为您可能有很多代码对于构建一个功能来说不是必需的。

我建议您运行某种预部署脚本,在调用

gcloud functions deploy
之前准备好您的函数。对于我为 Cloud Functions 运行的 monorepo,我有一个名为
bin/deploy.sh
的脚本,它接受函数路径作为参数,例如
bin/deploy.sh functions/testFunction
。它在部署前执行许多任务作为保障:

  1. cd functions/testFunction
  2. yarn install --immutable --immutable-cache --mode=skip-build
    必须检查它的包裹
  3. yarn tsc
    以确保它构建
  4. yarn eslint .
    以确保它是有效的
  5. yarn vitest run
    确保测试通过
  6. functions/testFunction/bin/deploy.sh
    为该单个函数运行自定义的
    gcloud functions deploy
    命令

有了这个,我不再依赖 Cloud Build 为我运行

tsc
;我通过
gcloud functions deploy
发送的所有内容都已经构建并准备好部署。如果您仍希望 Cloud Build 为您运行
tsc
,那么您可以在脚本中添加一个步骤,在部署之前修改
tsconfig.json
,然后撤消更改:

mv -f tsconfig.json tsconfig.testFunction.json && # Rename existing file
  cp -f ../tsconfig.json . &&                     # Copy parent file to this function
  gcloud functions deploy ... ;                   # Deploy the function and regardless of success or failure run the next command
  mv -f tsconfig.testFunction.json tsconfig.json  # Restore the original file
© www.soinside.com 2019 - 2024. All rights reserved.