为什么浏览器看不到我的模块?

时间:2017-05-20 20:41:51

标签: javascript ecmascript-6

Google Chrome 58.0.3029.110(64位)
ECMAScript 6

我学习JavaScript并阅读了解ECMAScript 6 一书。 ECMAScript 6定义了模块概念。

我写了几个js文件并将它们附加到我的html文件中。其中一个是脚本,另一个是模块。但谷歌Chrome浏览器没有看到我的js模块。为什么会这样?

这是我的HTML:

ItemsSource="{Binding Path=dFileList, ElementName=mainWindow}"

这是我的剧本:

<!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>

这是我的模块:

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

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

结果如下:

enter image description here

2 个答案:

答案 0 :(得分:2)

大多数浏览器尚不支持模块。 Safari 10.1实现了它们。在Chrome Canary中,您需要按照@SkinnyJ的说明启用支持。

但是你仍然需要解决代码中的一些问题:

<!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();

这适用于Safari 10.1和Chrome Canary,并启用了chrome:// flags / #enable-experimental-web-platform-features。

答案 1 :(得分:1)

ES6模块目前在“{Web}平台”标志后面的Chrome Canary中可用。它们不适用于“稳定”的Chrome。

相关问题