ES6 import gives Unexpected Identifier SyntaxError when running on terminal

旧时模样 提交于 2020-01-16 19:24:10

问题


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

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.


回答1:


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.



来源:https://stackoverflow.com/questions/56279455/es6-import-gives-unexpected-identifier-syntaxerror-when-running-on-terminal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!