Localhost未加载模块

时间:2019-03-05 15:36:18

标签: javascript module

我正在使用现代Javascript MyClass.js

export default class MyClass {
  constructor(x) {
    this.val=x? x: "Hello!"
    console.log("MyClass:",x)
  }
}

在我的http://localhost/myfolder/mypage.htm上(以下来源)

<!DOCTYPE html>
<html>
<head>
    <title>test</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel='shortcut icon' type='image/x-icon' href='./favicon.ico' />
    <script type="module" src="./MyClass.js"></script>

    <script>
    'use strict';

    document.addEventListener('DOMContentLoaded', function(){

    alert(123)
    let x = new MyClass(11);

    }, false); //ONLOAD
    </script>

</head>
<body> <p>Hello1!</p> </body>
</html>

为什么控制台说“未捕获的ReferenceError:未定义MyClass”

PS:这个问题是this other about using ES6+ with browser+NodeJs的补充。


注意:使用UBUNTU或Apache的Localhost ... myfolder到真实文件夹的符号链接有问题吗?在/var/www/html,我使用了ln -s /home/user/myRealFolder/site myfolder

1 个答案:

答案 0 :(得分:2)

您需要先导入模块,然后再使用

<!DOCTYPE html>
<html>
<head>
    <title>test</title>
    <meta charset="utf-8" />
    <script type="module" src="./MyClass.js"></script>
    <script type="module" id="m1">
      // script module is an "island", not need onload.
      'use strict';
      import MyClass from './MyClass.js';
      let x = new MyClass(11);     // we can use here...
      console.log("debug m1:", x)  // working fine!

      window.MyClassRef = MyClass; // "globalizing" class
      window.xRef = x              // "globalizing" instance
    </script>
    <script> // NON-module global script
    document.addEventListener('DOMContentLoaded',function(){
       // only works after all modules loaded:
       console.log("debug:", window.xRef) // working fine!
       let x = new window.MyClassRef(22); // using class also here,
       console.log("debug:", x)           // working fine!

    }, false); //ONLOAD
    </script>

</head>
<body> <p>Hello1!</p> </body>
</html>

有两种使用导入类的方法:

  1. 位于模块作用域(脚本m1):您可以使用new MyClass()
    并“全球化”实例(例如xRef)或构造函数的类(MyClassRef)。

  2. 处于全局范围:要与其他库一起使用或与主脚本一起使用,请使用全局引用,例如new window.MyClassRef()

所有这些解决方案都依赖于“静态导入” ...


可选的动态导入

您也可以使用 import ,其默认默认设置为<script>(不使用type="module"),也可以不使用“ onload”,而使用this solution,而不是最后一个脚本:

    <script>
    'use strict';
    import('./MyClass.js').then(({default: MyClass}) => {
       alert(123)  // async block
       let x = new MyClass(11);
     });
    </script>

请参见dynamic import