本地html文件中的script标签引入ES6的模块,直接在浏览器中打开该html文件,发现报错了:Uncaught SyntaxError: Cannot use import statement outside a module
对应的index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="./indexes.js"></script>
</body>
</html>
对应的indexes.js:
import cal from './calculatores.js'
console.log('sum: ', cal.add(1,2))
对应的calculatores.js:
export default {
add: function(a, b) {
return a + b
}
}
这里报错的原因是用了es6的语法, 浏览器默认将它作为js解析会出现问题,需要将它作为模块导入,script标签默认type="text/javascript",需要改为type="module",更改后的index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="module" src="./indexes.js"></script>
</body>
</html>
在浏览器中打开,发现又报错了:Access to script at 'file:///E:/**********/indexes.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.
从错误提示看,脚本是被跨域策略给拦截了,跨域请求只支持这些协议:http, data, chrome, chrome-extension, chrome-untrusted, https.,而我们的协议是file,这里我们需要本地起一个服务器来作为资源的提供方,简单的方式是安装VSCode的一个扩展Live Server
该插件安装完成后,在index.html页面右键选择Open with Live Server
然后就可以成功运行了:
从url上我们可以看到,Live Server为我们默认启动的服务器地址是127.0.0.1,端口号为5500,这样就解决跨域的问题啦!