[英]How to define const in Firebase Cloud Functions Typescript
The error that I am getting: Unhandled error ReferenceError: COLLECTION_A is not defined.我得到的错误:未处理的错误 ReferenceError: COLLECTION_A 未定义。 When I upload code is no complaints about the code.
当我上传代码时没有抱怨代码。 I do have a need to use the same constant in multiple files.
我确实需要在多个文件中使用相同的常量。 I tried to use
namespace
but it is not allowed...我尝试使用
namespace
,但不允许...
How do I need to define constants that will be accessible in every file?我如何需要定义可以在每个文件中访问的常量?
I have multiple files in src foldes:我在 src 文件夹中有多个文件:
index.ts索引.ts
foo.ts脚.ts
boo.ts靴子
cnst.ts cnst.ts
Inside index.ts:在 index.ts 中:
import * as admin from 'firebase-admin'
admin.initializeApp()
export * from './foo'
export * from './boo'
Inside cnst.ts: cnst.ts 内部:
const COLLECTION_A = "pathA"
const COLLECTION_B = "pathB"
Inside foo.ts I am trying to access const from cnst.ts在 foo.ts 我试图从 cnst.ts 访问 const
...
admin
.firestore()
.collection(COLLECTION_A)
...
I figured out!我想通了! But I don't like it!
但是我不喜欢!
Is there any better approach??有没有更好的办法?? Or more correct in terms of good practice.
或者在良好实践方面更正确。 I don't like this approach very much as a variable can be changed, But it should be const!!
我不太喜欢这种方法,因为可以更改变量,但它应该是 const !
inside cnst.ts I defined a new class:在 cnst.ts 我定义了一个新的 class:
export class Const {
static COLLECTION_A = "pathA"
static COLLECTION_B = "pathB"
}
And inside foo.ts I import it like this:在 foo.ts 我这样导入它:
import { Const } from './cnst'
...
...
.collection(Const.COLLECTION_A)
...
I figured out also approach with constants:我还想出了使用常量的方法:
inside cnst.ts在cnst.ts里面
export const COLLECTION_A = "pathA"
export const COLLECTION_B = "pathB"
And inside foo.ts I import it like this:在 foo.ts 我这样导入它:
import { COLLECTION_A } from './cnst'
...
...
.collection(COLLECTION_A)
...
I like second approach more since I am using constants.我更喜欢第二种方法,因为我使用的是常量。 Is there any other way that would be suitable for my case?
还有其他适合我的情况的方法吗?
Another approach is to use the outFile
flag.另一种方法是使用
outFile
标志。 According to Typescript documentation this flag allows user to:根据Typescript 文档,此标志允许用户:
Concatenate and emit output to single file.
将 output 连接并发出到单个文件。 The order of concatenation is determined by the list of files passed to the compiler on the command line along with triple-slash references and imports.
连接的顺序由命令行上传递给编译器的文件列表以及三斜杠引用和导入决定。
This strategy will scale with your program much better than manually referencing specific files everywhere.与在任何地方手动引用特定文件相比,此策略将更好地适应您的程序。
Check documentation for more details.查看文档以获取更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.