JavaScript 模組與 module 的基礎指南

更新日期: 2025 年 1 月 3 日

本文為 JS 動態載入 案例探討,第 3 篇

  1. 使用 Vue 和 DOM 操作整合的最佳實踐指南
  2. JavaScript 動態載入 import() 與靜態載入 import 指南
  3. JavaScript 模組與 module 的基礎指南 👈 所在位置
  4. JavaScript 動態載入模組|運行邏輯指南(附流程圖)

模組是 JavaScript 中提升代碼結構化和可維護性的重要工具。

模組允許我們將不同功能拆分到獨立的文件中,並通過清晰的接口進行共享和使用。

在動態導入模組的過程中,你會經常遇到 module,它代表所加載模組的內容。

這篇文章將從基礎概念到實際應用,幫助新手理解模組與 module 的用法及其差異。


什麼是模組?

模組的基本概念

模組是 JavaScript 中的一個獨立代碼單位,用於封裝功能。

通過模組,你可以:

  1. 提高可維護性:將代碼劃分為清晰的功能區塊,避免全域變數污染。
  2. 實現重用:模組可以被多次導入,減少重複代碼。

模組標準

現代 JavaScript 使用 ES6 模組標準,支持兩個核心操作:

  • 導出(Export):將模組中的功能或數據公開。
  • 導入(Import):在其他地方使用已公開的功能。

動態導入中的 module 是什麼?

module 的定義

當你使用 import() 動態導入模組時,module 是返回的一個物件,包含該模組中所有導出的內容。

範例

假設模組 switching_tab.js

export function init() {
  console.log("Switching tab initialized.");
}
export const version = "1.0";

動態導入 switching_tab.js

import("./scripts/switching_tab.js").then((module) => {
  console.log(module); // 打印導出的內容
  module.init();       // 使用模組的 `init` 函數
});

打印結果:

{
  init: function init(),   // 導出的 init 函數
  version: "1.0"           // 導出的 version 變數
}

解釋

  • module 是一個物件,包含模組中所有用 export 導出的項目。
  • 動態導入後,你可以通過物件訪問這些項目。

模組的導出與導入

命名導出(Named Exports)

導出多個命名項目:

// switching_tab.js
export function init() {
  console.log("Init tab");
}
export const version = "1.0";

靜態導入:

import { init, version } from "./scripts/switching_tab.js";
init();           // "Init tab"
console.log(version); // "1.0"

動態導入:

import("./scripts/switching_tab.js").then((module) => {
  module.init();           // "Init tab"
  console.log(module.version); // "1.0"
});

默認導出(Default Exports)

導出默認內容:

// toggling_buttons.js
export default function toggleButtons() {
  console.log("Toggling buttons");
}

靜態導入:

import toggle from "./scripts/toggling_buttons.js";
toggle(); // "Toggling buttons"

動態導入:

import("./scripts/toggling_buttons.js").then((module) => {
  module.default(); // "Toggling buttons"
});

模組的用途

代碼拆分

模組讓每個文件專注於處理特定功能,提升代碼結構的清晰度。

  • 範例
    • switching_tab.js 處理標籤切換功能。
    • toggling_buttons.js 處理按鈕切換功能。

按需加載

通過動態導入(import()),僅在需要時載入模組,減少初始頁面加載時間。

重用代碼

模組可以在多個地方導入,避免重複實現相同的功能。


模組與 module 的差異

項目模組(Module)module 物件
定義獨立的文件,封裝功能動態導入返回的物件,包含模組的導出內容
作用將代碼模組化訪問模組導出的項目
使用場景代碼拆分、功能隔離動態導入後,操作模組內容

完整示例:模組的動態導入

文件結構

scripts/
├── app.js              (主應用)
├── switching_tab.js     (切換標籤模組)
├── toggling_buttons.js  (切換按鈕模組)

切換標籤模組:switching_tab.js

export function init() {
  console.log("Switching tab initialized!");
}
export const version = "1.0";

切換按鈕模組:toggling_buttons.js

export function init() {
  console.log("Toggling buttons initialized!");
}

主應用:app.js

const pageElement = document.querySelector('[data-page]');
const pageName = pageElement ? pageElement.dataset.page : null;

if (pageName === "switching_tab") {
  import("./scripts/switching_tab.js").then((module) => {
    module.init();
    console.log(`Switching tab module version: ${module.version}`);
  });
} else if (pageName === "toggling_buttons") {
  import("./scripts/toggling_buttons.js").then((module) => {
    module.init();
  });
}

HTML

<div data-page="switching_tab"></div>
<script type="module" src="/scripts/app.js"></script>

總結

  • 模組(Module) 是 JavaScript 的核心單位,用於組織代碼。
  • module 物件 是動態導入返回的結果,包含模組的所有導出項目。
  • 動態導入 (import()) 提供了靈活的按需加載能力,特別適合大型應用的性能優化。

透過理解和運用模組化設計,你將能夠開發結構清晰、高效的 JavaScript 應用!

Similar Posts

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *