直接引用带有import关键字的JS脚本会报错

一般情况下我们通过<script>标签来引用JS脚本

<script src="123.js"></script>

但是在某些情况下,JS脚本会带有ES6的import关键字用来导入其他模块,比如:

//123.js
import ABC from "./ABC.js";
ABC("Hello World");

//ABC.js
export default function (String) {
    console.log(String);
}

↑ 示例脚本如上 ↑

Uncaught SyntaxError: Unexpected identifier

浏览器出现错误:提示不识别该脚本中的import标识符

<script type="module" src="ABC.js"></script>

修复浏览器错误:显式指定脚本类型为“Module”

Access to script at 'file:///C:/123.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.
GET file:///C:/123.js net::ERR_FAILED

浏览器依然报错,提示被CORS策略阻止,不能直接通过文件路径引用带有import关键字的JS脚本

不使用服务器,不编译这些脚本文件,不使用第三方工具
只在纯Chrome浏览器上进行调试,那么该如何解决跨域这个问题?

阅读 9.4k
4 个回答

搬运一个 stackoverflow 答案:

Most browser implementations by default do not support CORS headers for local files (specifically they set the value to null which cannot then be used in an Access-Control-Allow header.)

The easiest thing to do is start a small server. If you've got Python installed, this is as easy as running python3 -m http.server 8000 in the C:/Users/PCName/desktop directory, and then you can browse to localhost:8000 (there are other 'instant servers' out there!).

That way you can use Access-Control-Allow-*.

大部分浏览器不支持本地文件的 CORS header 。所以你要么起一个服务,要么关掉 CORS。

如果无法解决问题,可以“开除”提出问题的“人”啊,把chrome的CORS关掉

不知道要求'不适用服务器是因为什么',本地安装一个node http-server,这个问题就解决了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题