1

Node version:

node -v
v12.13.0

I read this documentation about using ES modules in Node.js:

Node.js will treat as CommonJS all other forms of input, such as .js files where the nearest parent package.json file contains no top-level "type" field

This is my package.json file:

{
  "type": "module",
  "name": "sandbox",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node ./src/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "ramda": "^0.26.1"
  }
}

this is my ./src/index.js:

import R from "ramda";
const src = {name:"Bob",age:7};
const _src = R.clone(src);
console.log(_src);

I try to start my code via npm start or node ./src/index.js but I get the error:

import R from "ramda";
^^^^^^

SyntaxError: Cannot use import statement outside a module

Why does it happen? I.e. why node ignores my "type": "module" setting?

At the same time it works fine:

node --experimental-modules .\src\index.js
Andrey Bushman
  • 11,712
  • 17
  • 87
  • 182

1 Answers1

1

In Node 12 you need to run node with the --experimental-modules flag to enable support for ECMAScript modules.

import is part of ES6, it not yet supported in NodeJS by default. it could be working by replacing import with require. Or you can use .babelrec as answered here.

Also For ES module usage, the value of "main" must be a full path including extension: "./src/index.js", not "index.js".

{
  "type": "module",
  "main": "./src/index.js"
  "scripts": {
    "start": "node --experimental-modules ./src/index.js"  
  },
}
Nima Bastani
  • 185
  • 11
  • > *At last ramda should get import with...* Why? My code works too as I see... – Andrey Bushman Nov 12 '19 at 12:53
  • I've tried this with Node v8.11.4, at first. `import R from 'ramda' trowed me an _ SyntaxError: _ The requested module does not provide an export named 'default', then I change it to what I've suggested and everything works, at the time i was using `.mjs` extension for my index file as was suggested in docs for that version for being able to use modules. I then update my Node to V12 and didn't change any of the code,just rename `index.js`. – Nima Bastani Nov 12 '19 at 14:41