diff --git a/src/components/index.ts b/src/components/index.ts index 36ae1f9..7507236 100644 --- a/src/components/index.ts +++ b/src/components/index.ts @@ -7,7 +7,7 @@ import './md-link'; export { Article } from './Article'; export type { ArticleProps } from './Article'; -// 导出类型 +// 导出数据类型 export type { DiceProps } from './dice'; export type { TableProps } from './table'; diff --git a/src/data-loader/index.ts b/src/data-loader/index.ts index b3a66e6..edca696 100644 --- a/src/data-loader/index.ts +++ b/src/data-loader/index.ts @@ -1,57 +1,56 @@ -/** - * 数据加载索引接口 - */ -export interface DataIndex { - [key: string]: string; -} - -/** - * 获取数据索引 - * 在 dev 环境使用 import.meta.glob 创建索引 - * 在 cli 环境检索目录创建并注入 - */ -export function getDataIndex(): DataIndex { - // @ts-ignore - import.meta.glob 在构建时会被处理 - if (typeof import.meta !== 'undefined' && import.meta.glob) { - // Dev 环境:使用 import.meta.glob 动态导入 - // @ts-ignore - const modules = import.meta.glob('../../content/**/*', { as: 'raw', eager: false }); - const index: DataIndex = {}; - for (const [path, importer] of Object.entries(modules)) { - const normalizedPath = path.replace('/src/', '/'); - index[normalizedPath] = normalizedPath; - } - return index; - } - - // CLI 环境:返回空索引,由 CLI 注入 - return {}; -} +let dataIndex: Record | null = null; +let isDevIndexLoaded = false; /** * 设置全局数据索引(CLI 环境使用) */ -export function setDataIndex(index: DataIndex) { - (window as any).__TTRPG_DATA_INDEX__ = index; +export function setDataIndex(index: Record) { + dataIndex = index; } /** - * 从全局索引获取数据 + * 从索引获取数据 */ function getIndexedData(path: string): string | null { - const index = (window as any).__TTRPG_DATA_INDEX__ as DataIndex | undefined; - if (index && index[path]) { - return index[path]; + if (dataIndex && dataIndex[path]) { + return dataIndex[path]; } return null; } +/** + * 在 dev 环境加载 glob 索引 + */ +async function loadDevIndex(): Promise { + if (isDevIndexLoaded) return; + isDevIndexLoaded = true; + + // @ts-ignore - import.meta.glob 在构建时会被处理 + if (typeof import.meta !== 'undefined' && import.meta.glob) { + try { + // @ts-ignore - 只加载 .csv 和 .md 文件 + const modules = import.meta.glob('../../content/**/*.{csv,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 不可用时忽略 + } + } +} + /** * 异步加载数据 * @param path 数据路径 * @returns 数据内容 */ export async function fetchData(path: string): Promise { + // dev 环境:先加载 glob 索引 + await loadDevIndex(); + // 首先尝试从索引获取 const indexedData = getIndexedData(path); if (indexedData) {