docs: clarify dev environment index loading behavior

Update file-index.ts documentation and implementation to specify
that webpackContext loading is restricted to development mode.
This ensures the code block is tree-shaken during production builds.
This commit is contained in:
hypercross 2026-07-08 15:19:50 +08:00
parent e0c3b8f4a0
commit 9a5ee695c2
1 changed files with 23 additions and 20 deletions

View File

@ -2,7 +2,7 @@
* *
* *
* 1. CLI /__CONTENT_INDEX.json * 1. CLI /__CONTENT_INDEX.json
* 2. Dev 使 webpackContext .md * 2. Dev 使 webpackContext .md dev
* 3. * 3.
* - IndexedDB * - IndexedDB
*/ */
@ -25,7 +25,7 @@ let activeDirHandle: FileSystemDirectoryHandle | null = null;
/** /**
* *
* CLI JSON webpack context * CLI JSON webpack context (dev only)
*/ */
function ensureIndexLoaded(): Promise<void> { function ensureIndexLoaded(): Promise<void> {
if (indexLoadPromise) return indexLoadPromise; if (indexLoadPromise) return indexLoadPromise;
@ -44,25 +44,28 @@ function ensureIndexLoaded(): Promise<void> {
// CLI 索引不可用时尝试下一个策略 // CLI 索引不可用时尝试下一个策略
} }
// 策略 2: Dev 环境 — webpackContext + raw loader // 策略 2: Dev 环境 — webpackContext + raw loader仅 dev 构建时生效)
try { // 生产构建时 process.env.NODE_ENV 被替换为 'production',整个分支会被 tree-shake 掉
const context = import.meta.webpackContext("../../content", { if (process.env.NODE_ENV === "development") {
recursive: true, try {
regExp: /\.md|\.yarn|\.csv$/i, const context = import.meta.webpackContext("../../content", {
}); recursive: true,
const keys = context.keys(); regExp: /\.md|\.yarn|\.csv$/i,
const index: FileIndex = {}; });
for (const key of keys) { const keys = context.keys();
const module = context(key) as { default?: string } | string; const index: FileIndex = {};
const content = for (const key of keys) {
typeof module === "string" ? module : (module.default ?? ""); const module = context(key) as { default?: string } | string;
const normalizedPath = "/content" + key.slice(1); const content =
index[normalizedPath] = content; typeof module === "string" ? module : (module.default ?? "");
const normalizedPath = "/content" + key.slice(1);
index[normalizedPath] = content;
}
fileIndex = { ...fileIndex, ...index };
activeSource = "webpack";
} catch (e) {
// webpackContext 不可用时忽略
} }
fileIndex = { ...fileIndex, ...index };
activeSource = "webpack";
} catch (e) {
// webpackContext 不可用时忽略
} }
// 策略 3: 浏览器 — 尝试从 IndexedDB 恢复保存的目录句柄 // 策略 3: 浏览器 — 尝试从 IndexedDB 恢复保存的目录句柄