ES6 module Import giving "Uncaught SyntaxError: Unexpected identifier"

JavascriptHtmlEcmascript 6Es6 Modules

Javascript Problem Overview


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 import line in main.js

I've got the following files:

assets/js/menu.module.js

'use strict';

export default class Menu
{ ... }

assets/js/main.js

import Menu from "./menu.module.js";

window.addEventListener('DOMContentLoaded', () => {
    const menu = new Menu();
});

index.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 import not being defined.

Chrome version would be 62, so according to different sources (including google's update log itself) this should be working, even without the flags.

Can anyone enlighten me as of why this is not working, and what I am doing wrong?

Javascript Solutions


Solution 1 - Javascript

As @Bergi mentioned in the comment, adding type="module" to the main.js import line in the HTML solved the issue. All is working now. I.e.

<script type="module" src="assets/js/main.js">

Thanks to all of you who responded and tried to help.

Solution 2 - Javascript

From what I can see you are trying to load the file menu.module.js while it's actually named menu.js.

PS: From what I recall you could also drop the .js from the import statement.

Solution 3 - Javascript

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.

 - npm i -D parcel@next
 - parcel index.html

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZeroThe2ndView Question on Stackoverflow
Solution 1 - JavascriptZeroThe2ndView Answer on Stackoverflow
Solution 2 - JavascriptMarcel KrauseView Answer on Stackoverflow
Solution 3 - JavascriptMuhammed MoussaView Answer on Stackoverflow