繁体   English   中英

Google Cloud Functions:尝试使用 ES6 时部署失败

[英]Google Cloud Functions: Deployment failure when attempting to use ES6

这个问题很相似,但没有帮助。

我们在 Google Cloud Functions 上使用 ES6 时看到此错误:

 Deployment failure: Build failed: /workspace/index.js:4 import { get } from 'axios'; ^ SyntaxError: Unexpected token { at new Script (vm.js:83:7) at

checkScriptSyntax (internal/bootstrap/node.js:620:5) 在 bootstrapNodeJSCore (internal/bootstrap/node.js:623:3) 启动时 (internal/bootstrap/node.js:280:11); 错误 ID:d984e68f

我们如何在 Google Cloud Function 中使用 ES6 语法?

代码:

/**
 * Required Modules
 */
import { get } from 'axios';
import { parseString } from 'xml2js';


/**
 * Responds to any HTTP request.
 *
 * @param {!express:Request} req HTTP request context.
 * @param {!express:Response} res HTTP response context.
 */
export async function run(req, res) {
  // Set API end point.
  let apiURL = 'https://www.w3schools.com/xml/note.xml';

  // Wrap API parameters in convenient object.
  let apiData = {
    PARAM_1: 'PARAM_DATA',
    PARAM_2: 'PARAM_DATA',
  };

  // Invoke API.
  get(apiURL,
    JSON.stringify(apiData)
  )
  .then((response) => {
    //res.status(200).send(response.data);

    let xmlData = response.data;

    parseString(xmlData, (err, result) => {
      if (err) {
        console.error(err);
   

 res.status(500).end();
    return;
  }
  res.status(200).send(result);
});

}, (error) => { res.status(500).send(response.data); 控制台日志(错误); }); }

Google Cloud Function Nodejs 运行时支持版本 10 和 12(测试版)

要在 Nodejs 版本 <= 12 中使用import { } from ""语法,您必须将文件另存为.mjs并使用--experimental-modules标志运行。 但是,Google Cloud Functions 不允许您传入标志,因此这不是此用例的选项

您可以使用babel ,或者转译和部署,或者使用babel-register ,或者跳过 babel 并使用esm 另一种选择是使用 Cloud Run,但这需要额外的步骤(即:docker)。

只需添加,在 Nodejs 版本 >= 13 中,您只需将{ "type": "module" }添加到 package.json (无需使用标志)。

暂无
暂无

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

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