/** * 数据加载索引接口 */ 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 {}; } /** * 设置全局数据索引(CLI 环境使用) */ export function setDataIndex(index: DataIndex) { (window as any).__TTRPG_DATA_INDEX__ = 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]; } return null; } /** * 异步加载数据 * @param path 数据路径 * @returns 数据内容 */ export async function fetchData(path: string): Promise { // 首先尝试从索引获取 const indexedData = getIndexedData(path); if (indexedData) { return indexedData; } // 索引不存在时,使用 fetch 加载 try { const response = await fetch(path); if (!response.ok) { throw new Error(`Failed to fetch: ${path}`); } return await response.text(); } catch (error) { console.error('fetchData error:', error); throw error; } }