代码之家  ›  专栏  ›  技术社区  ›  Pavel_K

在浏览器中,不执行从ES6模块导入的JS代码

  •  0
  • Pavel_K  · 技术社区  · 7 年前

    //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>
    

    2 回复  |  直到 7 年前
        1
  •  3
  •   Quentin    7 年前
       <script src="./mymodule.js" type="module"></script>
    

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

    import {TestClass} from "./mymodule";
    

    浏览器不像Node.js那样解析文件扩展名(它们不能,因为它们处理的是URL而不是文件系统,因此无法获取目录中的文件列表)。

    您需要明确的URL:

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

    page.html 通过HTTP而不是本地文件系统。

        2
  •  0
  •   André Teixeira    7 年前

    可以将类导出为默认关键字。

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