在终端上运行时,ES6导入会给出意外的标识符SyntaxError [英] ES6 import gives Unexpected Identifier SyntaxError when running on terminal

查看:180
本文介绍了在终端上运行时,ES6导入会给出意外的标识符SyntaxError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是整个ES6概念的新手,我目前正在尝试使用exportimport模块.我有一个简单的代码,只是logconsole的某些要求.下面是代码

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());

当我在终端上使用node运行代码时,出现此错误

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

在错误中,autoinrementId表示为printOut 当我使用module.exportsrequire时,一切正常.但是我想使用export import.我已经按照 https://babeljs.io/setup#installation

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

请问,我该如何解决这个问题,因为所有答案都已经读完了,所以告诉我在HTML中添加一个type="module",但是我正在终端上运行?谢谢.

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.

推荐答案

对于Node.js,请使用

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

该错误具有误导性,因为没有此标志,Node尝试将您的脚本解析为CommonJS模块而不是ES模块,而ES模块无法理解import/export.

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.

这篇关于在终端上运行时,ES6导入会给出意外的标识符SyntaxError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆