diff --git a/rsbuild.config.ts b/rsbuild.config.ts index a9c3c5d..49549be 100644 --- a/rsbuild.config.ts +++ b/rsbuild.config.ts @@ -16,6 +16,13 @@ export default defineConfig({ plugins: [tailwindcss()], }, }, + bundlerChain: (chain) => { + // 为 .md 文件配置 raw-loader,支持 webpackContext 加载 + chain.module + .rule('md-raw') + .test(/\.md$/) + .type('asset/source'); + }, }, html: { template: './src/index.html', diff --git a/src/data-loader/index.ts b/src/data-loader/index.ts index 2d4f4aa..612982b 100644 --- a/src/data-loader/index.ts +++ b/src/data-loader/index.ts @@ -42,23 +42,24 @@ export function ensureIndexLoaded(): Promise { // CLI 索引不可用时尝试 dev 环境 } - // Dev 环境:使用 import.meta.glob 加载 - if (typeof import.meta !== "undefined" && import.meta.glob) { - try { - // @ts-ignore - 只加载 .md 文件 - const modules = import.meta.glob("../../content/**/*.md", { - as: "raw", - eager: true, - }); - const index: Record = {}; - for (const [path, content] of Object.entries(modules)) { - const normalizedPath = path.replace("/src/", "/"); - index[normalizedPath] = content as string; - } - dataIndex = { ...dataIndex, ...index }; - } catch (e) { - // glob 不可用时忽略 + // Dev 环境:使用 import.meta.webpackContext + raw loader 加载 + try { + const context = import.meta.webpackContext("../../content", { + recursive: true, + regExp: /\.md$/, + }); + const keys = context.keys(); + const index: Record = {}; + for (const key of keys) { + // context 返回的是模块,需要访问其 default 导出(raw-loader 处理后的内容) + 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; } + dataIndex = { ...dataIndex, ...index }; + } catch (e) { + // webpackContext 不可用时忽略 } })();