ES6 import gives Unexpected Identifier SyntaxError when running on terminal

I am new to the whole ES6 concept and I am currently trying to use the export and import modules. I have a simple code that just logs something to the console. Below are the codes

autoincrementId.js

export default function autoincrementId() {
  return 'hey';
}

log.js

import autoincrementId from '../helpers/autoincrementId.js';

console.log(autoincrementId());

When I run my code with node on the terminal, I get this error screenshot of the error

The autoinrementId stands as the printOut in the error When I use the module.exports and require everything works fine. But I want to use the export import. I have already set up my environment using instructions from https://babeljs.io/setup#installation

Please, how do I fix this cause all answers have read on SO tells me to add a type="module" when in HTML but I am running on the terminal? Thanks.

Answers:

Answer

For Node.js, run the script with the --experimental-modules flag. This will allow you to use ES modules in Node.js without the need to transpile the import/export statements.

node --experimental-modules ./path/to/your.js

The error is sort of misleading because without this flag, Node is trying to parse your script as a CommonJS module instead of an ES module, which does not understand import/export.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.