问题
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 log
s 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