html引入模块
首先:引入模块需要在<script>中声明module否则报错
<script>
import { getSum } from "./index.js"
</script>
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/159efa13f25946d4f898184cefd2363c.jpeg)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1aeedf0c203af157ee04cafc9e5c7812.png)
声明的方式:
<script type="module">
import { getSum } from "./index.js"
let res = getSum(1, 2)
console.log(res)
</script>
这样模块就可以拿到对应方法所执行的结果
注意点:
1.每个模块都有自己的作用域,也就说即使.js的文件中变量名称重复也不会出现覆盖情况
2.模块也就是<script type='module'>在正常<script>的后面
3.模块中import { getSum } from "./index.js"必须作为头部使用(我的意思是不能使用判断语句加载)
<script type="module">
let content = true;
if (content) {
import { getSum } from "./index.js";
}
let res = getSum(1, 2)
console.log(res)
</script>
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/5073e009fb846b642e047374710a4d13.jpeg)
4.解决3中的动态加载问题
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c1bcf363a223430037c5dbabc950b27f.png)
5.导入的方式分类
(1).普通导入
import { getSum } from "./index.js"
(2).混合导入
import index,{getSum} from './index.js'
混合导入的第一个是随便起名的,但是需要在inde.js使用 export default这种
(3)全部导入
import * as index from "./index.js"
index.getSum();
这样方式并不好,因为如果使用打包工具,这里面所有的方法都会被打包,导致模块过大
(4).导入别名
import index,{ getSum as getSumFromIndex} from './index.js'
6.导出方式
(1).默认导出,这个的话允许有一个
export default{
get: function ( path = '',params = {} ) {
return new Promise(function (resolve, reject ) {
axios.get(path, {
params: params
}).then(function (response) {
resolve(response.data)
}).catch(function (err) {
reject(err);
})
})
}
}
在啰嗦一下:导入这个时候名字随便起的
import index(什么都可以) from "./index.js"
(2).多个导出
class User {
constructor(name) {
this.name = name;
}
getName() { return this.name; }
}
let site = 'www.baidu.com'
export {
User,
site
}
假如我只需导出一个常量,或者一个方法
export const getUserName = 'api/get/username';
export const getSumValue = (value1,value2) => {
return value1 + value2
}
来到需要的地方
<script>
import { name, getSumValue } from "./export.js"
console.log(getSumValue(1, 2))
</script>