使用es6中import和export报错

在学习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”

这样就可以运行了。亲测可用哦!

猜你喜欢

转载自blog.csdn.net/qq_42535651/article/details/104216237