之前我们在js文件中引用其它文件,可能是这样写
document.write("<script src='/include/script/md5.js' type='text/javascript'></script>");
然后在js文件里引用md5.js里的函数。
虽然这样能够实现,但不够结构化,而且不能实现按需导入。幸好es6提出了模块概念,现在大多数浏览器都已经支持了。
一、模块的导出导入
1)export 暴露给外部调用,如
export let a=1;
export function fun(x) {
//
}
当然也可以统一导出,如
export {a,fun};
注意,一般要写默认的导出变量
export default fun;
这样其它模块只导入一个变量时默认这个。
2)import 导入模块变量
如果上面的文件是1.js,那么导入是这样写
import {a,fun} from './md5.js';
fun(123);
注意:如果只导入一个变量,往往是默认的导出变量。
3)例子
md5.js
---------------------
const PI=3.1415926;
export {hex_md5,PI};
export default hex_md5;
public.js
---------------------
import {hex_md5,PI} from './md5.js';
function encodedPwd(str){
return hex_md5(str);
}
document.getElementById("btn").onclick=() =>{
document.getElementById("txt").value=encodedPwd("123456");
alert(PI);
}
二、动态导入
以往我们在js文件中引用其他文件时,会顶格写列,这样每次都必须加载文件。如果使用动态加载就做到了按需加载,并不需要每个文件都加载。
动态加载的语法:
import('/modules/mymodule.js')
.then((module) => {
// Do something with the module.
});
上面的示例改造一下:
public.js
---------------------
document.getElementById("btn").onclick=() =>{
import('/md5.js')
.then((module)=>{
document.getElementById("txt").value=module.hex_md5("123456");
alert(module.PI);
});
}
三、网页中调用
模块不用直接用本地路径的方式打开,会提示跨域的问题,应该配置到如IIS服务器中。
比如这里编写一个index.html配置到IIS服务器中
<html>
<head></head>
<body>
<input type="text" id="txt" />
<input type="button" id="btn" value="click me"/>
</body>
</html>
<script src="/public.js" type="module"></script>
运行网页,点击按钮就能看到效果了。
注意:引用模块,类型必须是type="module"。
或者这样使用
test2.js
---------------------
function test(){
import('./test1.js')
.then((module)=>{
alert(module.a);
});
}
index.html
---------------------
<html>
<head>
<script src="./test2.js"></script>
</head>
<body>
<input type="button" value="clickme" id="btn" />
</body>
</html>
<script>
document.getElementById("btn").onclick=function(){
test();
};
</script>