【问题标题】:ES6 import gives Unexpected Identifier SyntaxError when running on terminalES6 导入在终端上运行时给出 Unexpected Identifier SyntaxError
【发布时间】:2019-05-23 16:25:52
【问题描述】:

我是整个 ES6 概念的新手,我目前正在尝试使用 exportimport 模块。我有一个简单的代码,它只是 logs 到 console 的东西。下面是代码

autoincrementId.js

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

log.js

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

console.log(autoincrementId());

当我在终端上使用node 运行我的代码时,我收到了这个错误

autoinrementId 代表错误中的printOut 当我使用module.exportsrequire 时,一切正常。但我想使用exportimport。我已经按照https://babeljs.io/setup#installation的说明设置了我的环境

拜托,我该如何解决这个问题,因为所有答案都已阅读 SO 告诉我在 HTML 中添加 type="module" 但我在终端上运行?谢谢。

【问题讨论】:

  • 谢谢,@epascarello 解决了这个问题并编辑了问题,但这不是问题;

标签: javascript ecmascript-6 import export command-line-interface


【解决方案1】:

对于 Node.js,使用 --experimental-modules 标志运行脚本。这将允许您在 Node.js 中使用 ES 模块,而无需转换导入/导出语句。

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

这个错误有点误导,因为没有这个标志,Node 会尝试将您的脚本解析为 CommonJS 模块而不是 ES 模块,后者无法理解 import/export

【讨论】:

  • @WhiteHox 您使用的是什么版本的节点?可以node -v吗?
  • @WhiteHox 不需要更新。该版本应支持该标志。你是如何运行脚本的?你在用什么命令?我希望它类似于node --experimental-modules log.mjs
  • 是的@joseph,但它们必须在同一个目录中吗?
  • 哦!并且必须是.mjs 扩展名?
  • @WhiteHox 我不建议将实验标志下的任何东西推向生产(某些平台不允许你设置标志,所以你甚至不能使用它)。不过,这个功能预定是unflagged once v12 hits LTS status
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-07
  • 2019-07-26
  • 1970-01-01
  • 2019-05-08
  • 2018-07-03
  • 2020-06-09
相关资源
最近更新 更多