0

This question is similar, but did not help.

We see this error when using ES6 on Google Cloud Functions:

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) at startup (internal/bootstrap/node.js:280:11) at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3); Error ID: d984e68f

How can we use ES6 syntax with Google Cloud Function?

Code:

/**
 * 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); console.log(error); }); }

Crashalot
  • 33,605
  • 61
  • 269
  • 439

1 Answers1

4

Google Cloud Function Nodejs runtime supports version 10 and 12 (beta)

To use the import { } from "" syntax in Nodejs versions <= 12, you have to save the file as .mjs and run with the --experimental-modules flag. However, Google Cloud Functions don't allow you to pass in flags, so this is not an option for this use-case.

You could use babel, either transpile and deploy, or using babel-register, or skip babel and use esm. Another option would be to use Cloud Run, but that will require extra steps (ie: docker).

Just to add, in Nodejs versions >= 13, you only need to add { "type": "module" } to the package.json (no need to use the flag).

Jan Hernandez
  • 4,414
  • 2
  • 12
  • 18
nip
  • 1,609
  • 10
  • 20