Optional chaining operator gives SyntaxError when building my application to Heroku but works on my machine Optional chaining operator gives SyntaxError when building my application to Heroku but works on my machine heroku heroku

Optional chaining operator gives SyntaxError when building my application to Heroku but works on my machine


Does anyone know why is that?

Locally you're using a recent version of Node.js that supports the optional chaining operator. Apparently Heroku is using an older version of Node.js that doesn't. (Optional chaining is fairly new.)

I suspect I should compile the code first using Babel and then deploy to Heroku? Is it even related to Babel?

That's one option. We can tell that the version Heroku is using is < v14 because of the "ExperimentalWarning: The ESM module loader is experimental." According to this documentation that insivika pointed to, you can tell Heroku what version to use in the engines section of package.json, for instance:

{  "engines": {    "node": "14.x"  }}

That documentation says that the default is the current LTS version (as of this writing [07/Oct/2020], that's v12.x).

Or if this is the only place you're using optional chaining, you could use

object && object.optionalField && this.doSomething(object.optionalField);

or preferably

if (object && object.optionalField) {    this.doSomething(object.optionalField);}

;-)