2

Im trying to use native import which were released with node 12 but i always get this error even with importing just cors

import * as cors from 'cors';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Module._compile (internal/modules/cjs/loader.js:892:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
    at Module.load (internal/modules/cjs/loacjsder.js:812:32)
    at Function.Module._load (internal/modules/cjs/loader.js:724:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
    at internal/main/run_main_module.js:17:11

node version v12.13.0

docs https://nodejs.org/docs/latest-v12.x/api/esm.html#esm_code_import_code_specifiers which i tried to follow.

Thanks for help

  • Possible duplicate of [How can I use an es6 import in node?](https://stackoverflow.com/questions/45854169/how-can-i-use-an-es6-import-in-node) – Seblor Oct 25 '19 at 13:23
  • questioned asked Asked 2 years, 2 months ago this is new node 12 LTS – Markus Azer Oct 25 '19 at 13:27
  • 1
    The feature is still experimental (even though the node version 12 is LTS), so the answer is still valid. Just because the other question is old that doesn't mean the answer is outdated. – Seblor Oct 25 '19 at 13:27
  • :(, Node said that it will be available on 12, i thought that meant it will not be experimental anymore! I were waiting it patiently – Markus Azer Oct 25 '19 at 13:34
  • I didn't know about any official document stating it would be available (not experimental) in Node 12. However, you can still set up your project with babel (https://babeljs.io/en/setup) and use the ES6 modules, along with other ESNext features, like [decorators](https://github.com/tc39/proposal-decorators), or even the [optional chaining](https://github.com/tc39/proposal-optional-chaining) (After properly setting up the babel config & plugins). – Seblor Oct 25 '19 at 14:44

1 Answers1

1

You have to use this flag --experimental-modules while running node js, also you will have to us .mjs instead of .js extension

Mukesh Kumar
  • 684
  • 2
  • 7
  • 22
  • But its not experimetal anymore, its LTS since around 3 days ago https://medium.com/@nodejs/node-js-12-to-lts-and-node-js-13-is-here-e28d6a4a2bd – Markus Azer Oct 25 '19 at 13:25
  • @MarkusAzer it is still experimental in Node 13.0.1 according to the doc : https://nodejs.org/api/esm.html. I don't see any mention to ES6 imports in your linked article. – Seblor Oct 25 '19 at 13:25
  • Yes according to the documentation of Node 13.0.1 it's still in experimental phase – Mukesh Kumar Oct 25 '19 at 13:28