前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Uncaught SyntaxError: Cannot use import statement outside a module的解决方法(使用Es6语法引入js对象文件报错)

Uncaught SyntaxError: Cannot use import statement outside a module的解决方法(使用Es6语法引入js对象文件报错)

作者头像
超级小可爱
发布2023-02-20 16:03:33
1.4K0
发布2023-02-20 16:03:33
举报
文章被收录于专栏:小孟开发笔记小孟开发笔记

目录结构

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

对应的index.html:

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>休闲游戏</title>
</head>
<body>
<!--服务器访问路径http://test.com/pages/index/index.html-->
  你好
</body>
<script src="index.js"  ></script>
</html>

对应的indexes.js:

代码语言:javascript
复制
import app from '../../siteinfo.js'
// es6的语法---准备跳过jQuery直接使用面向对象的vue
console.log(app.domain);
代码语言:javascript
复制
对应的 siteinfo.js
代码语言:javascript
复制
import app from '../../siteinfo.js'
// es6的语法---准备跳过jQuery直接使用面向对象的vue
console.log(app.domain);

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

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>休闲游戏</title>
</head>
<body>
<!--服务器访问路径http://test.com/pages/index/index.html-->
  你好
</body>
<script src="index.js" type="module"></script>
</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,也可以使用PHPstudy搭建站点

本案例PHPstudy搭建站点

正常运行啦!

未经允许不得转载:肥猫博客 » Uncaught SyntaxError: Cannot use import statement outside a module的解决方法(使用Es6语法引入js对象文件报错)

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档