zl程序教程

您现在的位置是:首页 >  其他

当前栏目

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

2023-03-07 09:49:28 时间

目录结构

本地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">
    <title>休闲游戏</title>
</head>
<body>
<!--服务器访问路径http://test.com/pages/index/index.html-->
  你好
</body>
<script src="index.js"  ></script>
</html>

对应的indexes.js:

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

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

<!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对象文件报错)