简体   繁体   中英

“Unexpected token import” implementing native ES6 modules

I need to refactor some JavaScript code and am trying to implement ES6 modules using the native import/export commands. I struggled for awhile to get this working, so I am going to document what needed done here for future reference.

The symptom is that I receive the following message in the Chrome console:

Uncaught SyntaxError: Unexpected token import

My basic code for testing is:

HTML:

<!DOCTYPE html>
<html>
<body>
<h1>Import test</h1>
</body>
<script type="application/javascript" src="./import.js"></script>
</html>

import.js:

import { apath } from './alert_path';

alert_path.js:

export function apath() {
    alert('Bang!!!');
}

There were two actions I had to take to resolve this problem.

First, Chrome must be at 61+ or chrome://flags must enable Experimental Web Platform features.

Second, the script tag must use type module:

<!DOCTYPE html>
<html>
<body>
<h1>Import test</h1>
</body>
<script type="module" src="./import.js"></script>
</html>

I found the second answer here under What are the basics?

Modules must be eventually included in your HTML with type="module", which can appear as an inline or external script tag.

OBTW, the sample will fail due to CORS violations after this is resolved unless it is run through a server but that is another question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM