JavaScript 模組 (ES Modules)
你問到了一個非常核心的現代 JavaScript 開發問題!將功能拆分成獨立的 .js 檔案,然後在需要的地方引入,這正是 JavaScript 模組 (ES Modules) 的標準作法。
步驟 1:準備你的專案檔案結構
下載 Day.js : 前往Day.js 官網 或直接從 CDN 連結下載 dayjs.min.js 檔案。建立檔案結構 : 你的專案資料夾看起來應該像這樣:your-extension/├── lib/ │ └── dayjs.min.js <-- 把下載的檔案放在這裡 ├── popup.html ├── popup.js <-- 你的主要邏輯檔案 ├── date-formatter.js <-- 我們要創建的新模組檔案 └── manifest.json
步驟 2:創建你的模組檔案 ( date-formatter.js )
// 1. 從你的本地檔案中引入 dayjs 模組import dayjs from './lib/dayjs.min.js';
// 2. 擴充 Date.prototype (你的原始程式碼)
// 這個檔案不需要 "export" 任何東西,因為它的目的就是執行一次,
// 產生一個「副作用 (side effect)」——也就是修改全域的 Date.prototype。
Date.prototype.toCustomFormatString = function(templateString) {
const dayjsDate = dayjs(this);
const formattedString = templateString
? dayjsDate.format(templateString)
: dayjsDate.format('YYYY-MM-DD HH:mm:ss');
return formattedString;
};
console.log("date-formatter.js 模組已載入並執行。"); // (可選) 用於除錯
步驟 3:在你的主檔案中 ( popup.js ) 使用它
// 1. 匯入你的格式化模組// 我們只需要匯入它來執行它,不需要從中接收任何變數
import './date-formatter.js';
// --- 現在,你可以立即開始使用 toCustomFormatString() 方法了 ---
// 2. 你的應用程式主要邏輯
function initializePopup() {
const now = new Date();
const defaultFormat = now.toCustomFormatString();
console.log("預設格式:", defaultFormat);
const customFormat = now.toCustomFormatString('YYYY/MM/DD');
console.log("自訂格式:", customFormat);
// ... 你其他的 popup 邏輯 ...
}
// 執行
initializePopup();
步驟 4:【最關鍵的一步】告訴瀏覽器使用模組系統
對於 popup.js :
<html>
<head>
<!-- ... -->
</head>
<body>
<!-- ... 你的 HTML 內容 ... -->
<!-- 關鍵!加上 type="module" -->
<script src="popup.js" type="module"></script>
</body>
</html>
對於 background.js (Service Worker):
{ "manifest_version": 3,
"name": "我的擴充功能",
"version": "1.0",
"background": {
"service_worker": "background.js",
"type": "module" // 告訴 Chrome 這是一個 ES 模組
},
"action": {
"default_popup": "popup.html"
}
}```
然後在你的 `background.js` 中,你也可以像 `popup.js` 一樣使用 `import`。
### 總結
| 檔案 | 內容 | 目的 |
| :--- | :--- | :--- |
| **`dayjs.min.js`** | 第三方函式庫 | 提供強大的日期格式化功能。 |
| **`date-formatter.js`** | `import dayjs` 並擴充 `Date.prototype` | 創建一個可重用的、專門用來增強 `Date` 物件的模組。 |
| **`popup.js`** | `import './date-formatter.js'` | 你的應用程式主邏輯。匯入模組以啟用新功能,然後使用它。 |
| **`popup.html`** | `<script src="popup.js" type="module">` | **(關鍵)** 告訴瀏覽器以「模組模式」載入你的主腳本。 |
你提出的這個重構想法非常好,它能讓你的程式碼更有組織、更模組化,也更符合現代 JavaScript 的開發標準!
留言
張貼留言