写在前面:本文主要记录一下在html中引入es6模块化报错的问题
问题场景复现
在index.html文件中引入index.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>测试arrify</title>
</head>
<body>
<script src="./index.js">
</script>
</body>
</html>
在index.js文件中引入另外的模块js import arrify from 'arrify';
结果报错:
这个报错原因是因为使用了es6语法,浏览器默认将它作为js解析会出现问题,需要将它作为模块导入。
解决方案
- 在script标签中添加type属性
<script src="./index.js" type="module"></script>
然后又有了另外的报错
这个报错是因为脚本被跨骑拦截了,请求只支持http, data, chrome, chrome-extension, chrome-untrusted, https这几种类型,而我们本地文件是以file:///开头的因此不支持被拦截了。
- 可以使用vscode里面的扩展插件Live Server。
2. 插件安装完成后,右键以插件的方式打开页面就可以正常访问了。