Javascript ES6 模块导入给出“Uncaught SyntaxError: Unexpected identifier”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47632562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ES6 module Import giving "Uncaught SyntaxError: Unexpected identifier"
提问by ZeroThe2nd
For a personal project, I'm trying to use ES6 import to write cleaner code. As first test, I'm writing an object that should generate a menu. The whole code is working when I'm directly loading up the class, yet when using the import and export in ES6, it gives an "Uncaught SyntaxError: Unexpected identifier" error on the importline in main.js
对于个人项目,我尝试使用 ES6 导入来编写更清晰的代码。作为第一个测试,我正在编写一个应该生成菜单的对象。当我直接加载类时,整个代码都在工作,但是在 ES6 中使用导入和导出时,它会import在行中给出“未捕获的语法错误:意外的标识符”错误main.js
I've got the following files:
我有以下文件:
assets/js/menu.module.js
资产/js/menu.module.js
'use strict';
export default class Menu
{ ... }
assets/js/main.js
资产/js/main.js
import Menu from "./menu.module.js";
window.addEventListener('DOMContentLoaded', () => {
const menu = new Menu();
});
index.html
索引.html
<script type="module" src="assets/js/menu.module.js"></script>
<script src="assets/js/main.js">
Note that these are only the relevant lines of code.
请注意,这些只是相关的代码行。
Using the <script type="module">line or not did not seem to make any difference for me. I do have both the chrome flags for experimental and ES6 Modules enabled, as without them I received an error about importnot being defined.
是否使用这<script type="module">条线对我来说似乎没有任何区别。我确实启用了实验性和 ES6 模块的 chrome 标志,因为没有它们,我收到了关于import未定义的错误。
Chrome version would be 62, so according to different sources (including google's update log itself) this should be working, even without the flags.
Chrome 版本为 62,因此根据不同的来源(包括谷歌的更新日志本身),即使没有标志,这也应该可以工作。
Can anyone enlighten me as of why this is not working, and what I am doing wrong?
任何人都可以启发我为什么这不起作用,以及我做错了什么?
采纳答案by ZeroThe2nd
As @Bergi mentioned in the comment, adding type="module"to the main.jsimport line in the HTML solved the issue. All is working now. I.e.
正如@Bergi 在评论中提到的,添加type="module"到main.jsHTML 中的导入行解决了这个问题。现在一切正常。IE
<script type="module" src="assets/js/main.js">
Thanks to all of you who responded and tried to help.
感谢所有做出回应并试图提供帮助的人。
回答by Marcel Krause
From what I can see you are trying to load the file menu.module.jswhile it's actually named menu.js.
从我所看到的,您正在尝试加载文件,menu.module.js而实际上它的名称是menu.js.
PS: From what I recall you could also drop the .jsfrom the import statement.
PS:据我所知,您也可以.js从 import 语句中删除。
回答by Muhammed Moussa
you can use any module bundler, one of the simple flexible solutions is parcel 2, it's beta right now but you can play with it.
您可以使用任何模块捆绑器,其中一种简单灵活的解决方案是parcel 2,它现在是测试版,但您可以使用它。
- npm i -D parcel@next
- parcel index.html

