我需要重构一些 JavaScript 代码,并尝试使用 native 导入/导出命令来实现 ES6 模块。我努力了一段时间才让这项工作正常进行,所以我将在此处记录需要完成的工作以供将来引用。
症状是我在 Chrome 控制台中收到以下消息:
Uncaught SyntaxError: Unexpected token import
我的基本测试代码是:
HTML:
<!DOCTYPE html>
<html>
<body>
<h1>Import test</h1>
</body>
<script type="application/javascript" src="./import.js"></script>
</html>
导入.js:
import { apath } from './alert_path';
alert_path.js:
export function apath() {
alert('Bang!!!');
}
最佳答案
我必须采取两项措施来解决这个问题。
首先,Chrome 必须为 61+ 或 chrome://flags 必须启用实验性网络平台功能。
其次,script标签必须使用type module:
<!DOCTYPE html>
<html>
<body>
<h1>Import test</h1>
</body>
<script type="module" src="./import.js"></script>
</html>
我找到了第二个答案here在什么是基础知识下?
Modules must be eventually included in your HTML with type="module", which can appear as an inline or external script tag.
顺便说一句,在解决此问题后,示例将因 CORS 违规而失败,除非它通过服务器运行,但这是另一个问题。
关于javascript - "Unexpected token import"实现原生 ES6 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46414004/