简体   繁体   English

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

[英]Why the browser doesn't see my module?

Google Chrome 58.0.3029.110 (64-bit) 谷歌浏览器58.0.3029.110(64位)
ECMAScript 6 ECMAScript 6

I learn JavaScript and read the Understanding ECMAScript 6 book. 我学习JavaScript,并阅读了《 理解ECMAScript 6》一书。 ECMAScript 6 defines the module conception. ECMAScript 6定义了模块概念。

I wrote couple js-files and attached them into my html file. 我写了几个js文件,并将它们附加到我的html文件中。 One of them is script and other is the module. 其中之一是脚本,另一个是模块。 But Google Chrome doesn't see my js-module. 但是Google Chrome浏览器看不到我的js模块。 Why does it happen? 为什么会发生?

This is my html: 这是我的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. Safari 10.1实现了它们。 In Chrome Canary you need to enable support as explained by @SkinnyJ. 在Chrome Canary中,您需要按照@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. 此功能可在启用了chrome:// flags /#enable-experimental-web-platform-features的Safari 10.1和Chrome Canary中使用。

ES6 modules are currently available in Chrome Canary behind the "Experimental Web Platform" flag. 目前, Chrome Canary中的“实验性Web平台”标志后面提供了ES6模块。 They are not available in "stable" Chrome. 它们在“稳定的” Chrome中不可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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