// 图片资源映射 - 使用静态导入确保构建时包含所有图片 const imageModules = import.meta.glob( "../assets/images/**/*.{png,jpg,jpeg,gif,svg,webp}", { eager: true }, ); const IMAGE_EXTENSIONS = [".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp"]; /** * 把传入路径规范化为相对 src/assets/images/ 的路径 * 兼容 `src/assets/images/foo.png`、`assets/images/foo.png`、`/foo.png`、`foo.png` 等写法 */ function normalizeImagePath(path: string): string { return path .replace(/\\/g, "/") .replace(/^\/+/, "") .replace(/^(?:src\/)?assets\/images\//, ""); } /** * 访问静态图片(src/assets/images/ 下的构建期资源) * 未命中时返回空字符串并告警,调用方据此回退 */ export const getStaticImage = (path: string): string => { const normalized = normalizeImagePath(path); const candidate = IMAGE_EXTENSIONS.some((ext) => normalized.endsWith(ext)) ? normalized : `${normalized}.png`; const module = imageModules[`../assets/images/${candidate}`] as | { default: string } | undefined; if (module && typeof module.default === "string") { return module.default; } console.warn( `[assets] 未找到图片 "${path}",请确认文件位于 src/assets/images/ 下并已提交。`, ); return ""; }; /** * 获取背景图片的 CSS url 值 * 找不到时返回 "none" */ export const getBackgroundImage = (path: string): string => { const imageUrl = getStaticImage(path); return imageUrl ? `url(${imageUrl})` : "none"; }; /** * 获取 public 文件夹中的资源路径(用于 Word 文档等非构建期资源) */ export const getPublicPath = (path: string): string => { // 移除开头的斜杠(如果有) const cleanPath = path.startsWith("/") ? path.slice(1) : path; // 使用 Vite 的 BASE_URL 环境变量来处理基础路径 return `${import.meta.env.BASE_URL}${cleanPath}`; };