作者:泡乙唐 | 来源:互联网 | 2023-02-09 12:06
有没有办法在Cloud Functions for Firebase中使用es6语法?
import functions from 'firebase-functions';
export const helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase!");
})
失败:
SyntaxError: Unexpected token import
Doug Stevens..
11
简短的回答是,不,你不能这样做 - 但是.它与云功能没有任何关系.它与节点有关.如果使用该命令node index.js
将节点指向index.js ,您将看到完全相同的错误.
关于为什么这是一个复杂问题的长期答案已经在一些博客中讨论过,例如这里和这里.
编辑:firebase CLI 现在支持使用TypeScript的项目,这使您可以访问ES7语法.它会自动将其编译为ES6,以便部署到云功能.
1> Doug Stevens..:
简短的回答是,不,你不能这样做 - 但是.它与云功能没有任何关系.它与节点有关.如果使用该命令node index.js
将节点指向index.js ,您将看到完全相同的错误.
关于为什么这是一个复杂问题的长期答案已经在一些博客中讨论过,例如这里和这里.
编辑:firebase CLI 现在支持使用TypeScript的项目,这使您可以访问ES7语法.它会自动将其编译为ES6,以便部署到云功能.
2> cgenco..:
啊,想通了.要使用ES6的功能,如import
和const
,甚至ES7的功能,如await
和async
,使用打字稿通过重命名index.js
来index.ts
.
这是我的index.ts
:
import * as functions from 'firebase-functions';
export const helloWorld = functions.https.onRequest((req, resp) => {
resp.send("Hello from Firebase!");
});
Atom也提示我生成一个functions/tsconfig.json
文件.我不确定这是否必要,但这是生成的内容:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"isolatedModules": false,
"jsx": "react",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"declaration": false,
"noImplicitAny": false,
"noImplicitUseStrict": false,
"removeComments": true,
"noLib": false,
"preserveConstEnums": true,
"suppressImplicitAnyIndexErrors": true,
"lib": ["es2015", "es2015.promise"]
},
"exclude": [
"node_modules",
"typings/browser",
"typings/browser.d.ts"
],
"compileOnSave": true,
"buildOnSave": false,
"atom": {
"rewriteTsconfig": false
}
}
这是由以下产生的输出firebase deploy --only functions
:
=== Deploying to 'PROJECTNAME'...
i deploying functions
i functions: ensuring necessary APIs are enabled...
i runtimeconfig: ensuring necessary APIs are enabled...
? runtimeconfig: all necessary APIs are enabled
? functions: all necessary APIs are enabled
i functions: preparing functions directory for uploading...
i functions: packaged functions (1.53 KB) for uploading
? functions: functions folder uploaded successfully
i starting release process (may take several minutes)...
i functions: creating function helloWorld...
? functions[helloWorld]: Successful create operation.
? functions: all functions deployed successfully!
? Deploy complete!
Project Console: https://console.firebase.google.com/project/PROJECTNAME/overview
Function URL (helloWorld): https://us-central1-PROJECTNAME.cloudfunctions.net/helloWorld
小注意:Cloud Functions环境运行节点6.9.1,它完全支持`const`.您可以在http://node.green上查看其他支持的功能
3> Sriram C G..:
可以通过完整步骤检查此链接:
I.不推荐使用:
https ://codeburst.io/es6-in-cloud-functions-for-firebase-959b35e31cb0
创建./functionsES6
并复制package.json
,yarn.lock
并index.js
从中复制./functions.
添加预设 ./functionsES6/package.json
当你在根路径./functionsES6 - Yarn Deploy
II.更新:
https ://codeburst.io/es6-in-cloud-functions-for-firebase-2-415d15205468
你可以使用这些 package.json