繁体   English   中英

使用 ES 模块系统部署 Firebase function 和 TypeScript 时出现问题

[英]Problem deploying Firebase function with TypeScript using ES Module system

我在使用 ES 模块系统部署从 Typescript 编译的 Firebase function 时遇到问题。

索引.ts

import * as functions from "firebase-functions";
import myGreeting from "./my-greeting";

export const helloWorld = functions.https.onRequest((request, response) => {
  response.send(myGreeting);
});

我的问候语.ts

export default "HELLO WORLD";

tsconfig.json

{
  "compilerOptions": {
    "module": "ES2020",
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "moduleResolution": "node",
    "outDir": "lib",
    "sourceMap": true,
    "strict": true,
    "target": "ES2020"
  },
  "compileOnSave": true,
  "include": [
    "src"
  ]
}

package.json

{
  "name": "functions",
  "scripts": {
    "build": "tsc",
    "build:watch": "tsc --watch",
    "serve": "npm run build && firebase emulators:start --only functions",
    "shell": "npm run build && firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "type": "module",
  "engines": {
    "node": "16"
  },
  "main": "lib/index.js",
  "dependencies": {
    "firebase-admin": "^10.2.0",
    "firebase-functions": "^3.21.0"
  },
  "devDependencies": {
    "typescript": "^4.6.4"
  },
  "private": true
}

这构建得很好,但是 TypeScript 编译器当然不会在 output 文件./lib/index.js的导入语句中包含.js扩展名。

然后,当我尝试部署函数时,出现以下错误:

Error: Failed to load function definition from source: Failed to generate manifest from function source: Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/my-project/functions/lib/my-greeting' imported from /my-project/functions-test/functions/lib/index.js

我需要能够导入一个 npm 库,该库使用从 TypeScript 编译的 ES 模块,不包含 .js 扩展名(它没有 commonjs 版本)。 由于我将节点 16 运行时用于我理解的函数,因此我应该能够运行针对 ES2020 的 ES 模块,但是有没有办法在 Firebase 函数运行时中设置--experimental-specifier-resolution=node标志?

如何让 function 在节点 16 Firebase 云运行时中部署/运行,而不部署为 commonjs 模块

2 行不通的解决方案及原因:

1.我不能只修改导入语句

在上面的例子中我可以改变

import myGreeting from "./my-greeting";

import myGreeting from "./my-greeting.js";

这将是一个非常不切实际的工作流程,但除此之外,问题是我使用的是一个 ES 模块库,它具有这些未修改的导入语句,从 TypeScript 构建,所以我绝对不想在 go 中更改所有导入语句以包含.js扩展名。

2. 我不能在tsconfig.json中使用"module": "CommonJS"

如果我将tsconfig.json compilerOptions 更改为"module": "CommonJS"并从package.json中取出"type": "module" ,我可以让上面的示例部署得很好,但这不是一个选项,因为我需要工作使用仅作为 ES 模块提供的库,它没有发布 CommonJS 版本。

您需要修改源代码(index.ts)中的导入

import myGreeting from "./my-greeting";

import myGreeting from "./my-greeting.js";

据我所知,TSC 不会修改导入语句。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM