在服务器环境下使用模块化,而不是‘Alt+B’使用文件系统直接在浏览器运行项目
这种方式会在将你的代码跑在本地服务器上(http://127.0.0.1/)
如果是直接通过文件系统运行代码,会报错,这是FILE协议导致的跨域问题
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.
在script标签里加上 type='module’
script标签的默认type属性是"text/javascript"
,将其typr设置为module,这样浏览器就会把引入的脚本识别为JS module,注意import的时候必须带上后缀名
示例代码
html部分
<!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">
import {a} from './a.js' //引入必须加.js后缀名
console.log(a) // 1
</script>
</body>
</html>
a.js部分
const a = '1'
export {a}