ES6已经支持模块化,但是直接使用import引入其他文件export的对象会报错
Uncaught SyntaxError: Unexpected token {
这是因为export/import 属于ES2015标准的内容,浏览器加载ES2015模块化代码也是标签,但是要加入type="module"属性,如下:
<script type='module'>
import {Canvas2D} from './canvas2d/Canvas2D.js';
let canvas2d = new Canvas2D(document.getElementById('canvas'));
canvas2d.drawText('Hello World!')
</script>
加上type="module"后会继续得到错误:
Access to script at 'file:///C:/Users/Desktop/test/tsProj/canvas2d/Canvas2D.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
这是跨域错误,从HTTP服务器加载文件就能解决这个问题,可以利用node安装lite-server搭建本地服务器
npm install lite-server --save-dev
完成安装后打开 package.json找到script项,输入如下命令:
"script":{
"dev":"lite-server"
}
打开Git输入npm ren dev命令就能运行lite-server了
如果不用服务器加载文件只用File协议本地加载,也可能报错
Failed to load module script: The server responded with a non-JavaScript MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.
网上查找原因找到这样一个问题和解释,感觉说的很对
回答如下: