2021-4-12
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- 注意这里的type 必须带上,否则会报Uncaught SyntaxError: Cannot use import statement outside a module 的致命错误-->
<script type="module">
//这里如果是引用默认的模块不需要加上小夸号
import hello , { userName , User } from "./module1.js";
console.log(userName);
console.log(hello("assd"));
let a = new User("asdasdd",999);
a.print();
//控制台输出结果如下
</script>
</body>
</html>
//module1.js
//关于模块知识
let userName = "pandacode";
function hello(name){
return "hello" + name;
}
class User
{
//构造函数
constructor(product,price){
this.product = product;
this.price = price;
}
//函数输出
print(){
console.log(this.product + this.price);
}
}
//模块可以对变量函数类进行导出
//但仅允许导出一个默认模块
export { userName , User , hello as default}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="module">
//如果使用命名空间,我们可以先看下这个对象
//此时默认模块的hello 被default代替
import * as namespace from "./module1.js";
console.log(namespace);
// import hello , { userName , User } from "./module1.js";
console.log(namespace.userName);
console.log(namespace.default("assd"));
let a = new namespace.User("asdasdd",999);
a.print();
</script>
</body>
</html>