如何在 Node.js 中使用 ES6 匯入?
自從 ES6 以來,JavaScript 在專案中使用 import 語句來包含模組方面有了標準化的方式。最初 Node.js 使用 require() 來匯入模組,但隨著更新,它也引入了 ES6 import。本文將解釋如何在 Node.js 中使用 ES6 import,為什麼它很重要,以及什麼是良好的實踐。
為什麼在 Node.js 中使用 ES6 匯入?
以下是一些您應該在 Node.js 中使用 ES6 匯入的關鍵原因:
- 現代語法:import 比 require() 匯入模組更好,因為它更簡潔高效。
- 搖樹最佳化:ES6 模組可以選擇支援搖樹最佳化,在構建過程中刪除所有未使用的程式碼。
- 一致性:在 ES6 的瀏覽器語法方面,使用 import 使您的指令碼在整個程式碼中保持一致。
如何在 Node.js 中實現 ES6 匯入?
我們在這裡列出了在 Node.js 中實現 ES6 匯入的重要步驟:
步驟 1:Node.js 支援 ES6 模組
從 Node.js v 12 開始,使用 .mjs 副檔名或在 package.json 檔案中使用 type: module 可以原生支援 ES6 模組。
檢查您的 Node.js 版本
node --version
步驟 2:配置您的專案以使用 ES6 模組
選項 1:使用 .mjs 副檔名
要指定 ES6 模組,請將您的檔名設定為 .mjs 副檔名。
選項 2:在建立捆綁包時,在 package.json 中新增 “type”: “module”
更新您的 package.json 以包含
{ "type": "module" }
步驟 3:使用 import 語法
這是一個使用 import 包含模組的示例
// Import a named export import { readFile } from 'fs/promises'; // Import the default export import express from 'express'; const app = express(); console.log('Server is running...');
4. 處理 CommonJS 相容性
如果您正在使用舊版本的 CommonJS 模組,請使用 createRequire 函式包含它們
import { createRequire } from 'module'; const require = createRequire(import.meta.url); const lodash = require('lodash');
5. 執行指令碼
使用 Node.js 執行您的指令碼
node index.mjs
在 Node.js 中使用 ES6 匯入的最佳實踐
我們列出了一些關於在 Node.js 中使用 ES6 匯入的最佳實踐建議。
- 避免混合使用匯入和 require:儘可能堅持使用一種模組系統風格,以便使用者更容易在它們之間切換。
- 使用絕對匯入:配置模組路徑以獲得更簡潔的程式碼。
- 利用搖樹最佳化:僅匯入您需要的部分。
- 升級舊版程式碼:逐步用 import 語句替換 require()。
常見錯誤及解決方案
以下是常見錯誤及其解決方案:
1. SyntaxError: Cannot use import statement outside a module
確保您的檔案是 .mjs 或在 package.json 中將 type 設定為 "module"。
2. Cannot Find Module
使用相對或絕對路徑匯入。
3. 混合 ESM 和 CommonJS 問題
使用 createRequire 實現相容性。
結論
Node 程式應採用 ES6 樣式的匯入以符合 JavaScript 的現代標準。它提高了程式碼的可讀性、效能以及可維護性。閱讀本指南中的說明並在您的 Node.js 應用程式中採用推薦的實踐,立即開始使用 ES6 匯入。
廣告