gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:58:09 25 4
gpt4 key购买 nike

谷歌浏览器 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!');
}

这是结果:

enter image description here

最佳答案

大多数浏览器尚不支持模块。 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。

关于javascript - 为什么浏览器看不到我的模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44090625/

25 4 0
文章推荐: iphone - 使具有较长水平行的 对移动设备更友好