簡體   English   中英

如何使用導入和導出在瀏覽器中進行本地測試

[英]How to test locally in a browser using import and export

根據如何在另一個 JavaScript 文件中包含 JavaScript 文件? ,瀏覽器已經支持直接加載 ECMAScript 模塊。

那么為什么這在我的本地計算機上不起作用

索引.html

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Page Title</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
</head>
<body>
    
    <script type="module">
        import { hello } from './hello.js'; // Or the extension could be just `.js`
        hello('world');
      </script>

</body>
</html>

你好.js

export function hello(text) {
    alert(text);
}

控制台不斷給我 CORS 錯誤

CORS 策略已阻止從源“null”訪問“file:///C:/Users/Dave/Desktop/JavascriptImportExport/hello.js”處的腳本:跨源請求僅支持協議方案:http,數據,鍍鉻,鍍鉻擴展,勇敢,鍍鉻不受信任,https。

您不能從file://協議 URL 加載模塊。

為此,您需要一個 web 服務器。 如果您正在使用 VS Code 並且只需要一個網絡服務器來測試和學習,我建議您安裝Live Server擴展。

錯誤消息已經告訴您:

Cross origin requests are only supported for protocol schemes: 
http, data, chrome, chrome-extension, brave, chrome-untrusted, https.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM