如何修復 \"無法在模組之外使用 import 語句\" 的錯誤

以下是如何修復 JavaScript 中的錯誤 “Uncaught SyntaxError: cannot use import statement outside a module” 的方法。 在從 JavaScript 文件中導入函數時,我遇到了這個錯誤:Uncaught SyntaxError: cannot use import statement outside a module。 這個錯誤的原因是:你正在嘗試使用 import 語句,但你不在 ES 模組中(ES module)。 這個錯誤可能發生在 Node.js 環境中或瀏覽器中。 首先,這是 Node.js 的解決方案:你需要在項目的文件夾中添加一個 package.json 文件,並加入以下內容: { "type": "module" } 對於瀏覽器,當你加載腳本時,需要在 script 標籤中添加 type 屬性並設置值為 module,像這樣: <script type="module" src="./file.js"></script> 而不是: <script src="./file.js"></script>

如何修復錯誤 \"unexpected token \"{\". import call expects exactly one argument\"

以下是修復 “SyntaxError: Unexpected token ‘{’. import call expects exactly one argument.” 錯誤的方法: 我在 Safari 中遇到了這個問題。在 Chrome 中,相同的問題顯示為 “Uncaught SyntaxError: Cannot use import statement outside a module”,但原因是一樣的。 我試圖加載一個使用 ES 模塊風格的腳本,當我注意到腳本沒有加載時,並且在瀏覽器控制台中出現了這個錯誤: "SyntaxError: Unexpected token '{'. import call expects exactly one argument." 修復這個問題的方法很簡單,只需要將 <script src="./file.js"></script> 替換為 <script type="module" src="./file.js"></script> 即可。