为了组织我的项目,我决定按照以下文档将我的云函数分散到多个文件中:https://firebase.google.com/docs/functions/organize-functions?gen=1st#write_functions_in_multiple_files
它工作得很好,但现在我想共享内部函数以避免代码重复。
这是我尝试过的:
我在根级别创建了一个 sharedFunctions.js 文件,其中包含一些测试函数,例如:
function sayHello1(){
console.log('Hello world1');
}
function sayHello2(){
console.log('Hello world2');
}
还有一个 testSharedFunction.js 文件包含:
const functions = require('firebase-functions');
const sharedFunc = require('./sharedFunctions');
// firebase deploy --only functions:testSharedFunction
exports.testSharedFunction = functions.https.onRequest((request, response) => {
sharedFunc.sayHello1();
return true;
});
但是当我尝试部署我的 testSharedFunction 函数来测试它时,我收到此错误: 错误:解析触发器时出错:找不到模块'./sharedFunctions
您是否知道可能出了什么问题,或者我如何成功实现这些内部共享功能?
感谢您的帮助, 本杰明
您没有从
sayHello1()
导出 sayHello2()
和 sharedFunctions.js
函数,这就是您收到此错误的原因。更新后的代码将是:
sharedFunctions.js:
exports.sayHello1 = function() {
console.log("Hello world1");
};
exports.sayHello2 = function() {
console.log("Hello world2");
};
并按如下方式导入主文件中的内容:
testSharedFunction.js:
const functions = require('firebase-functions');
const sharedFunc = require('./sharedFunctions');
// firebase deploy --only functions:testSharedFunction
exports.testSharedFunction = functions.https.onRequest((request, response) => {
sharedFunc.sayHello1();
sharedFunc.sayHello2();
return true;
});
您正在使用
CommonJS-style module exports in Node.js.
,但您应该尝试一下ES6 modules imports
,它将简化如下:sharedFunctions.js:
export function sayHello1() {
console.log("Hello world1");
}
export function sayHello2() {
console.log("Hello world2");
}
导入将变成:
testSharedFunction.js:
// following import is used with typescript
import * as functions from "firebase-functions";
import { sayHello1, sayHello2 } from "./functions";
export const helloWorld = functions.https.onRequest((request, response) => {
sayHello1();
sayHello2();
response.send(true);
})