簡體   English   中英

為什么瀏覽器看不到我的模塊?

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

谷歌瀏覽器58.0.3029.110(64位)
ECMAScript 6

我學習JavaScript,並閱讀了《 理解ECMAScript 6》一書。 ECMAScript 6定義了模塊概念。

我寫了幾個js文件,並將它們附加到我的html文件中。 其中之一是腳本,另一個是模塊。 但是Google Chrome瀏覽器看不到我的js模塊。 為什么會發生?

這是我的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>

這是我的腳本:

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

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

這是我的模塊:

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

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

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

結果如下:

在此處輸入圖片說明

大多數瀏覽器尚不支持模塊。 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();

此功能可在啟用了chrome:// flags /#enable-experimental-web-platform-features的Safari 10.1和Chrome Canary中使用。

目前, Chrome Canary中的“實驗性Web平台”標志后面提供了ES6模塊。 它們在“穩定的” Chrome中不可用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM