【问题标题】:In browser JS code that imports from ES6 module is not executed在浏览器中从 ES6 模块导入的 JS 代码不会被执行
【发布时间】:2019-03-27 16:04:51
【问题描述】:

我有一个 ES6 模块 (mymodule) 和 HTML 页面,其中包含用户打开页面时必须执行的 JS 代码。这是我的模块:

//mymodule.js
class TestClass {

    getString() {
        return "TestString";
    }
}
export {TestClass}

这是我的页面:

//page.html
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Page</title>
        <script src="./mymodule.js" type="module"></script>
    </head>
    <body>
        <h1>Hello World!</h1>
        <script type="module">
            import {TestClass} from "./mymodule";
            let test = new TestClass();                 
            console.log("OUTPUT: " + test.getString());
        </script>
    </body>
</html>

Page.html 和 mymodule.js 在同一个文件夹中,但是,当我在浏览器中打开 page.html 时,控制台上什么都没有(没有错误,没有输出) - 我使用的是 FF 62.0.3。如何解决?

【问题讨论】:

    标签: javascript html


    【解决方案1】:
       <script src="./mymodule.js" type="module"></script>
    

    以上不需要。你可以删除它。

    import {TestClass} from "./mymodule";
    

    浏览器不像 Node.js 那样做文件扩展解析。 (他们不能,因为他们处理的是 URL 而不是文件系统,所以没有办法获取目录中的文件列表)。

    你需要明确的 URL:

    import {TestClass} from "./mymodule.js";
    

    注意:您还需要通过 HTTP 而不是从本地文件系统加载 page.html

    【讨论】:

    • 只有一个问题——你从哪里得到的? exploringjs.com/es6/ch_modules.html#sec_modules-in-browsers,第 16.6.1.2 节,import $ from 'lib/jquery';。注意,它是没有文件扩展名的模块名称。
    • 我的记忆(结合测试你的代码和对它的编辑)
    • 你确定You also need to load page.html over HTTP and not from the local file system.?我从本地 FS 加载页面(双击文件),Firefox 加载 ES6 模块没有问题。
    【解决方案2】:

    您可以将您的课程导出为默认关键字。

    class TestClass {
        getString() {
            return "TestString";
        }
    }
    export default {TestClass}
    

    【讨论】:

    • 我只是展示了一个例子,实际上我有更多的课程(> 100)。此外,我想控制导入。
    猜你喜欢
    • 2021-11-03
    • 2016-02-12
    • 2019-05-19
    • 2016-09-16
    • 2019-03-04
    • 1970-01-01
    • 1970-01-01
    • 2018-11-06
    • 2020-09-21
    相关资源
    最近更新 更多