简体   繁体   中英

Why the browser doesn't see my module?

Google Chrome 58.0.3029.110 (64-bit)
ECMAScript 6

I learn JavaScript and read the Understanding ECMAScript 6 book. ECMAScript 6 defines the module conception.

I wrote couple js-files and attached them into my html file. One of them is script and other is the module. But Google Chrome doesn't see my js-module. Why does it happen?

This is my html:

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'/>
    <title>Sandbox</title>
    <script src='./js/module.js' type='module'></script>
    <script src='./js/script.js' type='text/javascript'></script>
</head>
<body>
</body>
</html>

This is my script:

/* ECMAScript 6
 * ./js/script.js
 */

function scriptFunction(){
    console.log('I am script function!');
}

This is my module:

/* ECMAScript 6
 * ./js/module.js
 */

function internalFunction(){
    console.log('I am internal!');
}

export function exportedFunction(){
    console.log('I am exported!');
}

This is the result:

在此处输入图片说明

Modules are not yet supported by most browsers. Safari 10.1 implements them. In Chrome Canary you need to enable support as explained by @SkinnyJ.

But still you'll have to fix some issues in your code:

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'/>
    <title>Sandbox</title>
    <script src='./js/module.js' type='module'></script>
    <script src='./js/script.js' type='module'></script>
</head>
<body>
</body>
</html>
/* ECMAScript 6
 * ./js/module.js
 */

function internalFunction() {
    console.log("I am internal!");
}

export function exportedFunction() {
    internalFunction();
    console.log("I am exported!");
}
/* ECMAScript 6
 * ./js/script.js
 */

import {exportedFunction} from "./module.js";

function scriptFunction() {
    console.log("I am script function!");
}
scriptFunction();
exportedFunction();

This works in Safari 10.1 and Chrome Canary with chrome://flags/#enable-experimental-web-platform-features enabled.

ES6 modules are currently available in Chrome Canary behind the "Experimental Web Platform" flag. They are not available in "stable" Chrome.

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