a.js中使用export导出flag,sum:
let flag = true;
function sum(num1, num2) {
return num1 + num2
}
if (flag) {
console.log(sum(1, 2));
}
export {
flag,
sum
}
b.js中使用import导入flag,sum:
import { flag, sum } from './a.js';
console.log(flag);
if (flag) {
console.log(sum(100, 200));
}
index.html引入a.js、b.js:
<!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" src="./a.js"></script>
<script type="module" src="./b.js"></script>
</body>
</html>
直接在浏览器中预览时报错:跨源请求仅支持协议方案
解决方法:
在VSCode中安装live server插件:
在index.html文件中右键:“Open with Live Server”,正常输出结果: