From 9a5ee695c27470757d905c0268871b48923dab65 Mon Sep 17 00:00:00 2001 From: hypercross Date: Wed, 8 Jul 2026 15:19:50 +0800 Subject: [PATCH] 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. --- src/data-loader/file-index.ts | 43 +++++++++++++++++++---------------- 1 file changed, 23 insertions(+), 20 deletions(-) diff --git a/src/data-loader/file-index.ts b/src/data-loader/file-index.ts index 79a99c7..7e60ab4 100644 --- a/src/data-loader/file-index.ts +++ b/src/data-loader/file-index.ts @@ -2,7 +2,7 @@ * 文件索引管理器 * 支持多种文件索引加载方式: * 1. CLI 环境:从 /__CONTENT_INDEX.json 加载 - * 2. Dev 环境:使用 webpackContext 仅加载 .md 文件 + * 2. Dev 环境:使用 webpackContext 仅加载 .md 文件(仅在 dev 构建中生效) * 3. 浏览器环境:用户选择本地文件夹,扫描文件索引 * - 支持 IndexedDB 持久化目录句柄,刷新页面无需重新选择 */ @@ -25,7 +25,7 @@ let activeDirHandle: FileSystemDirectoryHandle | null = null; /** * 加载文件索引(只加载一次) - * 尝试顺序:CLI JSON → webpack context → 已持久化的目录句柄 + * 尝试顺序:CLI JSON → webpack context (dev only) → 已持久化的目录句柄 */ function ensureIndexLoaded(): Promise { if (indexLoadPromise) return indexLoadPromise; @@ -44,25 +44,28 @@ function ensureIndexLoaded(): Promise { // CLI 索引不可用时尝试下一个策略 } - // 策略 2: Dev 环境 — webpackContext + raw loader - try { - const context = import.meta.webpackContext("../../content", { - recursive: true, - regExp: /\.md|\.yarn|\.csv$/i, - }); - const keys = context.keys(); - const index: FileIndex = {}; - for (const key of keys) { - const module = context(key) as { default?: string } | string; - const content = - typeof module === "string" ? module : (module.default ?? ""); - const normalizedPath = "/content" + key.slice(1); - index[normalizedPath] = content; + // 策略 2: Dev 环境 — webpackContext + raw loader(仅 dev 构建时生效) + // 生产构建时 process.env.NODE_ENV 被替换为 'production',整个分支会被 tree-shake 掉 + if (process.env.NODE_ENV === "development") { + try { + const context = import.meta.webpackContext("../../content", { + recursive: true, + regExp: /\.md|\.yarn|\.csv$/i, + }); + const keys = context.keys(); + const index: FileIndex = {}; + for (const key of keys) { + const module = context(key) as { default?: string } | string; + const 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 恢复保存的目录句柄