【发布时间】:2019-11-26 08:22:37
【问题描述】:
我正在尝试使用 Typescript 从头开始构建我的 GCF 项目。我对这个项目(以及这个问题)的目标是了解云功能的工作原理并手动执行所有设置步骤,这就是我不复制任何示例代码或使用自动化工具的原因。
首先,这是我的src/index.ts 文件:
export const helloWorld = (req: any, res: any) => {
res.send('Hello, world 4');
}
在我运行 typescript 编译器后,我得到了这个 dist/index.js 文件,这似乎非常合理:
"use strict";
exports.__esModule = true;
exports.helloWorld = function (req, res) {
res.send('Hello, world 4');
};
我的package.json 设置为指向此文件:
{
"main": "dist/index.js",
"scripts": {
"start": "npx tsc-watch --onSuccess 'npx @google-cloud/functions-framework --target=helloWorld'",
"deploy": "gcloud functions deploy helloWorld --runtime nodejs10 --trigger-http"
},
"dependencies": {
"@google-cloud/functions-framework": "^1.1.2",
"tsc-watch": "^2.2.1",
"typescript": "^3.5.3"
}
}
我想先设置本地测试环境,所以我使用了functions framework。当我运行它时,一切正常:
$ npx @google-cloud/functions-framework --target=helloWorld
Serving function...
Function: helloWorld
URL: http://localhost:8080/
但是,当我尝试部署时,我收到此错误:
$ gcloud functions deploy helloWorld --runtime nodejs10 --trigger-http
Created .gcloudignore file. See `gcloud topic gcloudignore` for details.
Deploying function (may take a while - up to 2 minutes)...failed.
ERROR: (gcloud.functions.deploy) OperationError: code=3, message=Function failed on loading user code. Error message: Provided code is not a loadable module.
Could not load the function, shutting down.
为什么它说我的index.js 不是可加载模块,我该如何解决这个错误?
更新
原来gcloud 不尊重package.json 的main 字段。当我指定它应该使用--source 标志明确地使用dist 文件夹时,它部署了文件:
gcloud functions deploy helloWorld --source=dist/ --runtime nodejs10 --trigger-http
但是,它仍然不起作用,因为它似乎假定 所有内容,包括 package.json,都包含在此目录中 - 因此它不会链接任何库依赖项。
【问题讨论】:
标签: node.js typescript google-cloud-functions