ES6模块化使用

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.

网上查找原因找到这样一个问题和解释,感觉说的很对
在这里插入图片描述
回答如下:
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值