使用es6中import和export报错

梦想与她 提交于 2020-02-08 03:41:12

在学习import和export时,写了一个小demo进行测试

//index.html

<script>
import test from './test.js'
test()
</script>
//test.js
export default function (){
console.log('调用了test.js里的export函数了哦')
}

可是会报错CORS,因为是在本地进行测试的。
Access to script at ‘file:///C:/Users/hp/Desktop/test/test.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.

所以会有同源问题。把代码放到服务器上后,没了同源问题,但是会报
(index):21 Uncaught SyntaxError: Cannot use import statement outside a module

原因是必须在一个module中使用import
因而解决方法是在引入 包含有import的js的标签上加入 type=“module”

这样就可以运行了。亲测可用哦!
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!