Bak*_*ura 5 javascript browser module server
我正在开发一个使用本地服务器的项目。
在这个项目中,我使用模块,所以我的index.html包含:
<script src="js/index.js" type="module"></script>
Run Code Online (Sandbox Code Playgroud)
我的index.js包含:
import {} from "/js/randomModule.js";
import {} from "/js/randomModule.js";
...
Run Code Online (Sandbox Code Playgroud)
一切都运行得很完美,但是当我想在没有服务器的情况下直接在浏览器上使用该项目时,这就是问题:
Access to the script at 'file:///C:/Users/myFolder/js/index.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.
index.html:54
GET file:///C:/Users/myFolder/js/index.js net::ERR_FAILED
Run Code Online (Sandbox Code Playgroud)
那么,有没有一种方法可以type="module"在浏览器中直接使用javascript而不需要服务器呢?
小智 7
\n\n\n您需要注意本地测试 \xe2\x80\x94 如果您尝试在本地加载\nHTML 文件(即使用 file:// URL),由于 JavaScript 模块安全要求,您将遇到 CORS\n错误。您需要通过服务器进行\n测试。
\n
遗憾的是,没有,你不能在没有服务器的情况下直接在浏览器中运行带有“type=\'module\'”的 JS。
\n有很多选项可以运行本地服务器:W/X/LAMP 堆栈、oldschool php -S localhost:8080、带有express.js 和静态目录的节点等。
您不能使用 file:// 协议来执行此操作,如 MDN 文档中所述: