如何通过File://协议在网页中使用“导入”功能

时间:2019-04-09 20:17:15

标签: ecmascript-6

大多数浏览器都支持“导入”,因此以下各项应能工作:

/**
* Adder.mjs
*/

class Adder {

    add(n1, n2) {
        return n1 + n2;
    }
}

export default Adder;

test.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Import Test</title>
<script type="module">
    import Adder from "./Adder.mjs";
    var adder = new Adder();
    var result = adder.add(1, 1);
    console.log("Result: " + result.toString());
</script>
</head>
<body>
</body>
</html>

但是它导致以下错误(Chromium调试控制台):

Access to script at 'file:///home/gso/eclipse-workspace/Test/Adder.js' from origin 'null' has been blocked by CORS policy: The response is invalid.
test.html:7 GET file:///home/gso/eclipse-workspace/Test/Adder.js net::ERR_FAILED

1 个答案:

答案 0 :(得分:-1)

正如connexo指出的:

  

“模块无法在file://协议上工作。您需要Web服务器。”

还值得注意的是Apache不支持.mjs文件扩展名,ES6模块必须带有后缀.js。