0

I try to use optional chaining in my nodeJS project.

I use version 15.8 (or any >12, I'm using nvm).

my project is run with flag esm

$ run.env -p ../../.env nodemon -r esm --watch ../../.env --watch ./src/ ./src/index.js
[nodemon] 2.0.12
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): ../../.env src/**/*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node -r esm ./src/index.js`
/home/dre/Projects/my/packages/backend/src/routes/account/login.js:72
    let user = await Account.findOne({ email: payload?.email });
                                                      ^

SyntaxError: Invalid or unexpected token
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
[nodemon] app crashed - waiting for file changes before starting...

My eslint is not yelling at this syntax anymore, but no way to have it understood for node.

Any idea would help me a lot!

dredtrake
  • 13
  • 4
  • What node version are you running? It's [not supported below version 14](https://stackoverflow.com/questions/59574047/how-to-use-optional-chaining-in-node-js-12)... – Alexander Nied Sep 28 '21 at 14:06
  • It should work fine in 15.8 though, are you sure that's the version nodemon uses? Try logging `process.version`. – CherryDT Sep 28 '21 at 14:09
  • Are you sure you don't have any older version of node on your system? And are you sure nodemon is using the correct version from nvm? – derpirscher Sep 28 '21 at 14:09
  • @AlexanderNied, @CherryDt, @derpirscher my version is 15.8 when I log the `process.versions` I got `{ node: '15.8.0', v8: '8.6.395.17-node.23', uv: '1.40.0', zlib: '1.2.11', brotli: '1.0.9', ares: '1.17.1', modules: '88', nghttp2: '1.42.0', napi: '7', llhttp: '2.1.3', openssl: '1.1.1i', cldr: '38.1', icu: '68.2', tz: '2020d', unicode: '13.0' }` – dredtrake Sep 28 '21 at 17:57

2 Answers2

0

You have to enable this feature as it is not widely supported by applying the --harmony flag which applies the new ECMAScript 6 features.

According to node.green, optional chaining will be supported starting with Node 14, but will still require the --harmony flag.

Nanyo
  • 87
  • 1
  • 10
  • I tried to run it with the flag, but having the same error `run.env -p ../../.env nodemon -r esm --harmony --watch ../../.env --watch ./src/ ./src/index.js` I also tried to use node instead of nodemon but no better result – dredtrake Sep 28 '21 at 18:01
  • @dredtrake I cant reproduce the issue. Can you create a new dir and run `npm init` in there then try using optional chaining with and without the harmony tag? – Nanyo Sep 30 '21 at 12:44
  • I think it was due to the architecture of my project, I have set it again and had no problems anymore :) – dredtrake Oct 01 '21 at 14:06
0

Updated to v16.10 removed the esm flag put "type": "module" in my package.json

I now need to adapt my app a bit to make it work and fix some new errors.

dredtrake
  • 13
  • 4