fix: data loading

This commit is contained in:
hypercross 2026-02-26 09:31:12 +08:00
parent d2a383c5d8
commit f4a6d6978b
2 changed files with 35 additions and 36 deletions

View File

@ -7,7 +7,7 @@ import './md-link';
export { Article } from './Article'; export { Article } from './Article';
export type { ArticleProps } from './Article'; export type { ArticleProps } from './Article';
// 导出类型 // 导出数据类型
export type { DiceProps } from './dice'; export type { DiceProps } from './dice';
export type { TableProps } from './table'; export type { TableProps } from './table';

View File

@ -1,57 +1,56 @@
/** let dataIndex: Record<string, string> | null = null;
* let isDevIndexLoaded = false;
*/
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 使 * CLI 使
*/ */
export function setDataIndex(index: DataIndex) { export function setDataIndex(index: Record<string, string>) {
(window as any).__TTRPG_DATA_INDEX__ = index; dataIndex = index;
} }
/** /**
* *
*/ */
function getIndexedData(path: string): string | null { function getIndexedData(path: string): string | null {
const index = (window as any).__TTRPG_DATA_INDEX__ as DataIndex | undefined; if (dataIndex && dataIndex[path]) {
if (index && index[path]) { return dataIndex[path];
return index[path];
} }
return null; return null;
} }
/**
* dev glob
*/
async function loadDevIndex(): Promise<void> {
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<string, string> = {};
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 * @param path
* @returns * @returns
*/ */
export async function fetchData(path: string): Promise<string> { export async function fetchData(path: string): Promise<string> {
// dev 环境:先加载 glob 索引
await loadDevIndex();
// 首先尝试从索引获取 // 首先尝试从索引获取
const indexedData = getIndexedData(path); const indexedData = getIndexedData(path);
if (indexedData) { if (indexedData) {