本地html文件中的script标签引入ES6的模块,直接在浏览器中打开该html文件,发现报错了:Uncaught SyntaxError: Cannot use import statement outside a module
报错
对应的index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script src="./indexes.js"></script>
</body>
</html>

对应的indexes.js:

import cal from './calculatores.js'

console.log('sum: ', cal.add(1,2))

对应的calculatores.js:

export default {
    add: function(a, b) {
        return a + b
    }
}

这里报错的原因是用了es6的语法, 浏览器默认将它作为js解析会出现问题,需要将它作为模块导入,script标签默认type="text/javascript",需要改为type="module",更改后的index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script type="module" src="./indexes.js"></script>
</body>
</html>

在浏览器中打开,发现又报错了:Access to script at 'file:///E:/**********/indexes.js' 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.
报错
从错误提示看,脚本是被跨域策略给拦截了,跨域请求只支持这些协议:http, data, chrome, chrome-extension, chrome-untrusted, https.,而我们的协议是file,这里我们需要本地起一个服务器来作为资源的提供方,简单的方式是安装VSCode的一个扩展Live Server
liveserver
该插件安装完成后,在index.html页面右键选择Open with Live Server

在这里插入图片描述
然后就可以成功运行了:
成功运行
url上我们可以看到,Live Server为我们默认启动的服务器地址是127.0.0.1,端口号为5500,这样就解决跨域的问题啦!

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐