来浏览器上使用原生模块需要在script标签上添加type=module属性
例如:
es.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div>ES模块化</div>
<script type=module src="./es.js"></script>
</body>
</html>
es.js
function total (a, b) {
return a * b;
}
import * as math from './math.js';
document.body.innerHTML = `PI = ${math.PI}`;
math.js
const PI = 3.14159;
export { PI as PI };
输出结果:
PI = 3.14159
特点:
1、作为模块加载的脚本不会像普通的 script 脚本一样污染全局作用域。
2、默认 defer,支持 async
3、同一模块执行一次(同一模块指相同的url 包括所带的参数)
4、 CORS 跨域限制 (常规的script标签的重要特点是不受CORS限制),而模块化的是受限的, script 标签type=module加强了这方面的安全策略,浏览器加载不同域的脚本资源时,如果服务器未返回有效的 Allow-Origin
相关 CORS 头,浏览器会禁止加载改脚本。
作者:weixin_34146805
来源:优快云
原文:https://blog.youkuaiyun.com/weixin_34146805/article/details/88029504
版权声明:本文为博主原创文章,转载请附上博文链接!