feat: 预制体系统与架构改进 (#303)
* feat(prefab): 实现预制体系统和编辑器 UX 改进 ## 预制体系统 - 新增 PrefabSerializer: 预制体序列化/反序列化 - 新增 PrefabInstanceComponent: 追踪预制体实例来源和修改 - 新增 PrefabService: 预制体核心服务 - 新增 PrefabLoader: 预制体资产加载器 - 新增预制体命令: Create/Instantiate/Apply/Revert/BreakLink ## 预制体编辑模式 - 支持双击 .prefab 文件进入编辑模式 - 预制体编辑模式工具栏 (保存/退出) - 预制体实例指示器和操作菜单 ## 编辑器 UX 改进 - SceneHierarchy 快捷键: F2 重命名, Ctrl+D 复制, ↑↓ 导航 - 支持双击实体名称内联编辑 - 删除实体时显示子节点数量警告 - 右键菜单添加重命名/复制选项及快捷键提示 - 布局持久化和重置功能 ## Bug 修复 - 修复 editor-runtime 组件类重复导致的 TransformComponent 不识别问题 - 修复 .prefab-name 样式覆盖导致预制体工具栏文字不可见 - 修复 Inspector 资源字段高度不正确问题 * feat(editor): 改进编辑器 UX 交互体验 - ContentBrowser: 加载动画 spinner、搜索高亮、改进空状态设计 - SceneHierarchy: 选中项自动滚动到视图、搜索清除按钮 - PropertyInspector: 输入框本地状态管理、Enter/Escape 键处理 - EntityInspector: 组件折叠状态持久化、属性搜索清除按钮 - Viewport: 变换操作实时数值显示 - 国际化: 添加相关文本 (en/zh) * fix(build): 修复 Web 构建资产加载和编辑器 UX 改进 构建系统修复: - 修复 asset-catalog.json 字段名不匹配 (entries vs assets) - 修复 BrowserFileSystemService 支持两种目录格式 - 修复 bundle 策略检测逻辑 (空对象判断) - 修复 module.json 中 assetExtensions 声明和类型推断 行为树修复: - 修复 BehaviorTreeExecutionSystem 使用 loadAsset 替代 loadAssetByPath - 修复 BehaviorTreeAssetType 常量与 module.json 类型名一致 (behavior-tree) 编辑器 UX 改进: - 构建完成对话框添加"打开文件夹"按钮 - 构建完成对话框样式优化 (圆形图标背景、按钮布局) - SceneHierarchy 响应式布局 (窄窗口自动隐藏 Type 列) - SceneHierarchy 隐藏滚动条 错误追踪: - 添加全局错误处理器写入日志文件 (%TEMP%/esengine-editor-crash.log) - 添加 append_to_log Tauri 命令 * feat(render): 修复 UI 渲染和点击特效系统 ## UI 渲染修复 - 修复 GUID 验证 bug,使用统一的 isValidGUID() 函数 - 修复 UI 渲染顺序随机问题,Rust 端使用 IndexMap 替代 HashMap - Web 运行时添加 assetPathResolver 支持 GUID 解析 - UIInteractableComponent.blockEvents 默认值改为 false ## 点击特效系统 - 新增 ClickFxComponent 和 ClickFxSystem - 支持在点击位置播放粒子效果 - 支持多种触发模式和粒子轮换 ## Camera 系统重构 - CameraSystem 从 ecs-engine-bindgen 移至 camera 包 - 新增 CameraManager 统一管理相机 ## 编辑器改进 - 改进属性面板 UI 交互 - 粒子编辑器面板优化 - Transform 命令系统 * feat(render): 实现 Sorting Layer 系统和 Overlay 渲染层 - 新增 SortingLayerManager 管理排序层级 (Background, Default, Foreground, UI, Overlay) - 实现 ISortable 接口,统一 Sprite、UI、Particle 的排序属性 - 修复粒子 Overlay 层被 UI 遮挡问题:添加独立的 Overlay Pass 在 UI 之后渲染 - 更新粒子资产格式:从 sortingOrder 改为 sortingLayer + orderInLayer - 更新粒子编辑器面板支持新的排序属性 - 优化 UI 渲染系统使用新的排序层级 * feat(ci): 集成 SignPath 代码签名服务 - 添加 SignPath 自动签名工作流(Windows) - 配置 release-editor.yml 支持代码签名 - 将构建改为草稿模式,等待签名完成后发布 - 添加证书文件到 .gitignore 防止泄露 * fix(asset): 修复 Web 构建资产路径解析和全局单例移除 ## 资产路径修复 - 修复 Tauri 本地服务器 `/asset?path=...` 路径解析,正确与 root 目录连接 - BrowserPathResolver 支持两种模式: - 'proxy': 使用 /asset?path=... 格式(编辑器 Run in Browser) - 'direct': 使用直接路径 /assets/path.png(独立 Web 构建) - BrowserRuntime 使用 'direct' 模式,无需 Tauri 代理 ## 架构改进 - 移除全局单例 - 移除 globalAssetManager 导出,改用 AssetManagerToken 依赖注入 - 移除 globalPathResolver 导出,改用 PathResolutionService - 移除 globalPathResolutionService 导出 - ParticleUpdateSystem/ClickFxSystem 通过 setAssetManager() 注入依赖 - EngineService 使用 new AssetManager() 替代全局实例 ## 新增服务 - PathResolutionService: 统一路径解析接口 - RuntimeModeService: 运行时模式查询服务 - SerializationContext: EntityRef 序列化上下文 ## 其他改进 - 完善 ServiceToken 注释说明本地定义的意图 - 导出 BrowserPathResolveMode 类型 * fix(build): 添加 world-streaming composite 设置修复类型检查 * fix(build): 移除 world-streaming 引用避免 composite 冲突 * fix(build): 将 const enum 改为 enum 兼容 isolatedModules * fix(build): 添加缺失的 IAssetManager 导入
This commit is contained in:
@@ -220,6 +220,36 @@ export interface WebBuildConfig extends BuildConfig {
|
||||
*/
|
||||
generateAssetCatalog?: boolean;
|
||||
|
||||
/**
|
||||
* Asset file extensions to copy (glob patterns).
|
||||
* 要复制的资产文件扩展名(glob 模式)。
|
||||
*
|
||||
* If not provided, uses default extensions.
|
||||
* If provided by plugins via AssetLoaderFactory.getAllSupportedExtensions(),
|
||||
* includes all registered loader extensions.
|
||||
*
|
||||
* 如果未提供,使用默认扩展名。
|
||||
* 如果通过 AssetLoaderFactory.getAllSupportedExtensions() 由插件提供,
|
||||
* 则包含所有已注册加载器的扩展名。
|
||||
*
|
||||
* @example ['*.png', '*.jpg', '*.particle', '*.bt']
|
||||
*/
|
||||
assetExtensions?: string[];
|
||||
|
||||
/**
|
||||
* Asset extension to type mapping.
|
||||
* 资产扩展名到类型的映射。
|
||||
*
|
||||
* Used by asset catalog generation to determine asset types.
|
||||
* If not provided, uses default mapping.
|
||||
*
|
||||
* 用于资产目录生成以确定资产类型。
|
||||
* 如果未提供,使用默认映射。
|
||||
*
|
||||
* @example { 'png': 'texture', 'particle': 'particle' }
|
||||
*/
|
||||
assetTypeMap?: Record<string, string>;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -729,21 +729,64 @@ ${userScriptImports}
|
||||
* Step 4: Copy asset files.
|
||||
* 步骤 4:复制资产文件。
|
||||
*/
|
||||
/**
|
||||
* Default asset extensions (base types only).
|
||||
* 默认资产扩展名(仅基础类型)。
|
||||
*
|
||||
* Plugin-specific extensions should be declared in module.json's assetExtensions field.
|
||||
* 插件特定的扩展名应在 module.json 的 assetExtensions 字段中声明。
|
||||
*/
|
||||
private static readonly DEFAULT_ASSET_EXTENSIONS = [
|
||||
// 图片 | Images
|
||||
'*.png', '*.jpg', '*.jpeg', '*.gif', '*.webp', '*.bmp', '*.svg',
|
||||
// 音频 | Audio
|
||||
'*.mp3', '*.ogg', '*.wav', '*.m4a', '*.aac', '*.flac',
|
||||
// 数据 | Data
|
||||
'*.json', '*.xml', '*.yaml', '*.yml',
|
||||
// 字体 | Fonts
|
||||
'*.ttf', '*.woff', '*.woff2', '*.otf',
|
||||
// 精灵和图集 | Sprites and Atlases
|
||||
'*.atlas', '*.fnt',
|
||||
// Note: Plugin-specific extensions (*.particle, *.btree, *.prefab, etc.)
|
||||
// are now declared in each module's module.json assetExtensions field.
|
||||
// 注意:插件特定的扩展名(*.particle, *.btree, *.prefab 等)
|
||||
// 现在在各模块的 module.json assetExtensions 字段中声明。
|
||||
];
|
||||
|
||||
private async _stepCopyAssets(context: BuildContext): Promise<void> {
|
||||
const fs = this._getFileSystem(context);
|
||||
const webConfig = context.config as WebBuildConfig;
|
||||
|
||||
const assetsDir = `${context.projectRoot}/assets`;
|
||||
const outputAssetsDir = `${context.outputDir}/assets`;
|
||||
|
||||
if (await fs.pathExists(assetsDir)) {
|
||||
const count = await fs.copyDirectory(assetsDir, outputAssetsDir, [
|
||||
'*.png', '*.jpg', '*.jpeg', '*.gif', '*.webp',
|
||||
'*.mp3', '*.ogg', '*.wav', '*.m4a',
|
||||
'*.json', '*.xml',
|
||||
'*.ttf', '*.woff', '*.woff2',
|
||||
'*.atlas', '*.fnt'
|
||||
]);
|
||||
console.log(`[WebBuild] Copied ${count} asset files`);
|
||||
// 优先级:1. 配置提供的扩展名 2. 模块声明的扩展名 3. 默认扩展名
|
||||
// Priority: 1. Config-provided extensions 2. Module-declared extensions 3. Default extensions
|
||||
let extensions: string[];
|
||||
|
||||
if (webConfig.assetExtensions && webConfig.assetExtensions.length > 0) {
|
||||
// 使用配置明确提供的扩展名
|
||||
// Use explicitly provided config extensions
|
||||
extensions = webConfig.assetExtensions;
|
||||
} else {
|
||||
// 从模块收集扩展名并与默认值合并
|
||||
// Collect from modules and merge with defaults
|
||||
const moduleExtensions = this._collectModuleAssetExtensions(context);
|
||||
const combinedPatterns = new Set([
|
||||
...WebBuildPipeline.DEFAULT_ASSET_EXTENSIONS,
|
||||
...moduleExtensions.patterns
|
||||
]);
|
||||
extensions = Array.from(combinedPatterns);
|
||||
|
||||
// 存储合并后的类型映射供后续步骤使用
|
||||
// Store merged type map for later steps
|
||||
context.data.set('moduleAssetTypeMap', moduleExtensions.typeMap);
|
||||
}
|
||||
|
||||
console.log(`[WebBuild] Using ${extensions.length} extension patterns: ${extensions.slice(0, 10).join(', ')}${extensions.length > 10 ? '...' : ''}`);
|
||||
const count = await fs.copyDirectory(assetsDir, outputAssetsDir, extensions);
|
||||
console.log(`[WebBuild] Copied ${count} asset files using ${extensions.length} extension patterns`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -798,6 +841,7 @@ ${userScriptImports}
|
||||
*/
|
||||
private async _stepGenerateCatalog(context: BuildContext): Promise<void> {
|
||||
const fs = this._getFileSystem(context);
|
||||
const webConfig = context.config as WebBuildConfig;
|
||||
|
||||
// Meta file format from asset-system-editor
|
||||
// 来自 asset-system-editor 的 meta 文件格式
|
||||
@@ -811,12 +855,14 @@ ${userScriptImports}
|
||||
}
|
||||
|
||||
// Use unified IAssetCatalog format from @esengine/asset-system
|
||||
// 使用 @esengine/asset-system 中统一的 IAssetCatalog 格式
|
||||
// 使用 @esengine/asset-system 中 IRuntimeCatalog 格式(运行时期望 assets 字段)
|
||||
// Use IRuntimeCatalog format from @esengine/asset-system (runtime expects assets field)
|
||||
const catalog = {
|
||||
version: '1.0.0',
|
||||
createdAt: Date.now(),
|
||||
loadStrategy: 'file' as const, // Web builds use file-based loading
|
||||
entries: {} as Record<string, {
|
||||
bundles: {} as Record<string, unknown>, // Required by IRuntimeCatalog
|
||||
assets: {} as Record<string, {
|
||||
guid: string;
|
||||
path: string;
|
||||
type: string;
|
||||
@@ -831,16 +877,25 @@ ${userScriptImports}
|
||||
const outputAssetsDir = `${context.outputDir}/assets`;
|
||||
const outputScenesDir = `${context.outputDir}/scenes`;
|
||||
|
||||
let totalMetaFiles = 0;
|
||||
let skippedNoGuid = 0;
|
||||
let skippedNoOutput = 0;
|
||||
let addedEntries = 0;
|
||||
|
||||
for (const dirName of sourceAssetDirs) {
|
||||
const sourceDir = `${context.projectRoot}/${dirName}`;
|
||||
if (!await fs.pathExists(sourceDir)) continue;
|
||||
|
||||
const metaFiles = await fs.listFilesByExtension(sourceDir, ['.meta'], true);
|
||||
const metaFiles = await fs.listFilesByExtension(sourceDir, ['meta'], true);
|
||||
totalMetaFiles += metaFiles.length;
|
||||
|
||||
for (const metaFile of metaFiles) {
|
||||
try {
|
||||
const meta = await fs.readJson<AssetMeta>(metaFile);
|
||||
if (!meta.guid) continue;
|
||||
if (!meta.guid) {
|
||||
skippedNoGuid++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const assetSourcePath = metaFile.replace(/\.meta$/, '');
|
||||
|
||||
@@ -861,29 +916,58 @@ ${userScriptImports}
|
||||
|
||||
relativePath = relativePath.replace(/\\/g, '/');
|
||||
|
||||
if (!await fs.pathExists(outputPath)) continue;
|
||||
if (!await fs.pathExists(outputPath)) {
|
||||
skippedNoOutput++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const size = await fs.getFileSize(outputPath);
|
||||
|
||||
catalog.entries[meta.guid] = {
|
||||
// 获取资产类型:
|
||||
// 1. 如果 meta.type 存在且不是 "custom",使用它
|
||||
// 2. 否则尝试从模块声明的扩展名推断
|
||||
// 3. 最后回退到 meta.type(可能是 "custom")
|
||||
// Get asset type:
|
||||
// 1. If meta.type exists and is not "custom", use it
|
||||
// 2. Otherwise try to infer from module-declared extensions
|
||||
// 3. Fall back to meta.type (may be "custom")
|
||||
let assetType = meta.type;
|
||||
const fileName = assetSourcePath.split(/[/\\]/).pop() || '';
|
||||
|
||||
// 如果类型是 "custom" 或空,尝试从模块扩展名推断
|
||||
// If type is "custom" or empty, try to infer from module extensions
|
||||
if (!assetType || assetType === 'custom') {
|
||||
const inferredType = this._getAssetTypeFromFileName(fileName, webConfig, context);
|
||||
// 只有推断出具体类型时才使用(不是 "data" 这种通用类型)
|
||||
// Only use inferred type if it's specific (not generic like "data")
|
||||
if (inferredType && inferredType !== 'data') {
|
||||
assetType = inferredType;
|
||||
} else if (!assetType) {
|
||||
assetType = inferredType || 'custom';
|
||||
}
|
||||
}
|
||||
|
||||
catalog.assets[meta.guid] = {
|
||||
guid: meta.guid,
|
||||
path: relativePath,
|
||||
type: meta.type || this._getAssetType(assetSourcePath.split('.').pop() || ''),
|
||||
type: assetType,
|
||||
size,
|
||||
hash: hashFileInfo(relativePath, size)
|
||||
};
|
||||
addedEntries++;
|
||||
} catch (error) {
|
||||
console.warn(`[WebBuild] Failed to process meta file: ${metaFile}`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
await fs.writeFile(
|
||||
`${context.outputDir}/asset-catalog.json`,
|
||||
JSON.stringify(catalog, null, 2)
|
||||
);
|
||||
|
||||
console.log(`[WebBuild] Generated asset catalog: ${Object.keys(catalog.entries).length} assets, strategy=${catalog.loadStrategy}`);
|
||||
console.log(`[WebBuild] Generated asset catalog: ${Object.keys(catalog.assets).length} assets, strategy=${catalog.loadStrategy}`);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -901,7 +985,7 @@ ${userScriptImports}
|
||||
let mainScenePath = './scenes/main.ecs';
|
||||
const scenesDir = `${context.outputDir}/scenes`;
|
||||
if (await fs.pathExists(scenesDir)) {
|
||||
const sceneFiles = await fs.listFilesByExtension(scenesDir, ['.ecs', '.scene']);
|
||||
const sceneFiles = await fs.listFilesByExtension(scenesDir, ['ecs', 'scene']);
|
||||
if (sceneFiles.length > 0) {
|
||||
const sceneName = sceneFiles[0].split(/[/\\]/).pop();
|
||||
mainScenePath = `./scenes/${sceneName}`;
|
||||
@@ -1755,15 +1839,156 @@ ${pluginLoads}
|
||||
</html>`;
|
||||
}
|
||||
|
||||
private _getAssetType(ext: string): string {
|
||||
const typeMap: Record<string, string> = {
|
||||
'png': 'texture', 'jpg': 'texture', 'jpeg': 'texture', 'gif': 'texture', 'webp': 'texture',
|
||||
'mp3': 'audio', 'ogg': 'audio', 'wav': 'audio', 'm4a': 'audio',
|
||||
'json': 'data', 'xml': 'data',
|
||||
'ttf': 'font', 'woff': 'font', 'woff2': 'font',
|
||||
'atlas': 'atlas', 'fnt': 'font'
|
||||
};
|
||||
return typeMap[ext] || 'binary';
|
||||
/**
|
||||
* Default extension to type mapping (base types only).
|
||||
* 默认扩展名到类型的映射(仅基础类型)。
|
||||
*
|
||||
* Plugin-specific mappings should be declared in module.json's assetExtensions field.
|
||||
* 插件特定的映射应在 module.json 的 assetExtensions 字段中声明。
|
||||
*/
|
||||
private static readonly DEFAULT_ASSET_TYPE_MAP: Record<string, string> = {
|
||||
// 图片 | Images
|
||||
'png': 'texture', 'jpg': 'texture', 'jpeg': 'texture', 'gif': 'texture',
|
||||
'webp': 'texture', 'bmp': 'texture', 'svg': 'texture',
|
||||
// 音频 | Audio
|
||||
'mp3': 'audio', 'ogg': 'audio', 'wav': 'audio', 'm4a': 'audio',
|
||||
'aac': 'audio', 'flac': 'audio',
|
||||
// 数据 | Data
|
||||
'json': 'data', 'xml': 'data', 'yaml': 'data', 'yml': 'data',
|
||||
// 字体 | Fonts
|
||||
'ttf': 'font', 'woff': 'font', 'woff2': 'font', 'otf': 'font', 'fnt': 'font',
|
||||
// 精灵图集 | Sprite Atlas
|
||||
'atlas': 'atlas',
|
||||
// Note: Plugin-specific types (particle, behavior-tree, prefab, tilemap, etc.)
|
||||
// are now declared in each module's module.json assetExtensions field.
|
||||
// 注意:插件特定的类型(particle, behavior-tree, prefab, tilemap 等)
|
||||
// 现在在各模块的 module.json assetExtensions 字段中声明。
|
||||
};
|
||||
|
||||
/**
|
||||
* Cached type map from config (merged with defaults).
|
||||
* 从配置缓存的类型映射(与默认值合并)。
|
||||
*/
|
||||
private _assetTypeMap: Record<string, string> | null = null;
|
||||
|
||||
/**
|
||||
* Get asset type by extension.
|
||||
* 根据扩展名获取资产类型。
|
||||
*
|
||||
* Priority: config.assetTypeMap > moduleAssetTypeMap > DEFAULT_ASSET_TYPE_MAP
|
||||
* 优先级:配置类型映射 > 模块类型映射 > 默认类型映射
|
||||
*/
|
||||
private _getAssetType(ext: string, config?: WebBuildConfig, context?: BuildContext): string {
|
||||
const lowerExt = ext.toLowerCase();
|
||||
|
||||
// 1. 配置提供的类型映射
|
||||
// 1. Config-provided type map
|
||||
if (config?.assetTypeMap) {
|
||||
if (!this._assetTypeMap) {
|
||||
// 合并默认值和配置
|
||||
// Merge defaults and config
|
||||
const moduleTypeMap = context?.data.get('moduleAssetTypeMap') as Record<string, string> || {};
|
||||
this._assetTypeMap = {
|
||||
...WebBuildPipeline.DEFAULT_ASSET_TYPE_MAP,
|
||||
...moduleTypeMap,
|
||||
...config.assetTypeMap
|
||||
};
|
||||
}
|
||||
return this._assetTypeMap[lowerExt] || 'binary';
|
||||
}
|
||||
|
||||
// 2. 模块声明的类型映射
|
||||
// 2. Module-declared type map
|
||||
if (context) {
|
||||
const moduleTypeMap = context.data.get('moduleAssetTypeMap') as Record<string, string> | undefined;
|
||||
if (moduleTypeMap && moduleTypeMap[lowerExt]) {
|
||||
return moduleTypeMap[lowerExt];
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 默认类型映射
|
||||
// 3. Default type map
|
||||
return WebBuildPipeline.DEFAULT_ASSET_TYPE_MAP[lowerExt] || 'binary';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get asset type from full filename, supporting compound extensions.
|
||||
* 从完整文件名获取资产类型,支持复合扩展名。
|
||||
*
|
||||
* @param fileName - File name (e.g., "explosion.particle.json")
|
||||
* @param config - Build config
|
||||
* @param context - Build context
|
||||
* @returns Asset type string
|
||||
*/
|
||||
private _getAssetTypeFromFileName(fileName: string, config?: WebBuildConfig, context?: BuildContext): string {
|
||||
const lowerName = fileName.toLowerCase();
|
||||
|
||||
// 检查模块声明的复合扩展名
|
||||
// Check module-declared compound extensions
|
||||
const moduleTypeMap = context?.data.get('moduleAssetTypeMap') as Record<string, string> | undefined;
|
||||
if (moduleTypeMap) {
|
||||
// 优先检查复合扩展名(按长度排序,最长优先)
|
||||
// Prioritize compound extensions (sorted by length, longest first)
|
||||
const sortedExts = Object.keys(moduleTypeMap).sort((a, b) => b.length - a.length);
|
||||
for (const ext of sortedExts) {
|
||||
if (lowerName.endsWith(ext)) {
|
||||
return moduleTypeMap[ext];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 回退到简单扩展名
|
||||
// Fallback to simple extension
|
||||
const simpleExt = fileName.split('.').pop() || '';
|
||||
return this._getAssetType(simpleExt, config, context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert glob patterns to plain extension list for listFilesByExtension.
|
||||
* 将 glob 模式转换为 listFilesByExtension 所需的简单扩展名列表。
|
||||
*
|
||||
* @param patterns - Glob patterns like ['*.png', '*.jpg']
|
||||
* @returns Plain extensions like ['png', 'jpg']
|
||||
*/
|
||||
private _globPatternsToExtensions(patterns: string[]): string[] {
|
||||
return patterns
|
||||
.map(p => {
|
||||
// Remove *. prefix if present
|
||||
const match = p.match(/^\*\.(.+)$/);
|
||||
return match ? match[1].toLowerCase() : p.toLowerCase();
|
||||
})
|
||||
.filter(ext => ext.length > 0 && !ext.includes('*'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect asset extensions from all enabled modules.
|
||||
* 从所有启用的模块收集资产扩展名。
|
||||
*
|
||||
* @param context - Build context containing module list
|
||||
* @returns Glob patterns and type map
|
||||
*/
|
||||
private _collectModuleAssetExtensions(context: BuildContext): {
|
||||
patterns: string[];
|
||||
typeMap: Record<string, string>;
|
||||
} {
|
||||
const allModules = context.data.get('allModules') as ModuleManifest[] || [];
|
||||
const patterns: string[] = [];
|
||||
const typeMap: Record<string, string> = {};
|
||||
|
||||
for (const module of allModules) {
|
||||
if (module.assetExtensions) {
|
||||
for (const [ext, type] of Object.entries(module.assetExtensions)) {
|
||||
// 转换为 glob 模式 | Convert to glob pattern
|
||||
const cleanExt = ext.startsWith('.') ? ext.substring(1) : ext;
|
||||
patterns.push(`*.${cleanExt}`);
|
||||
|
||||
// 添加类型映射 | Add type mapping
|
||||
typeMap[cleanExt.toLowerCase()] = type;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { patterns, typeMap };
|
||||
}
|
||||
|
||||
private _getStatusForStep(stepId: string): BuildStatus {
|
||||
@@ -2044,27 +2269,44 @@ ${userScriptImports}
|
||||
const assetsDir = `${context.projectRoot}/assets`;
|
||||
if (await fs.pathExists(assetsDir)) {
|
||||
console.log('[WebBuild] Inlining assets...');
|
||||
const assetExtensions = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'mp3', 'ogg', 'wav', 'ttf', 'woff', 'woff2', 'json'];
|
||||
|
||||
// 优先级:1. 配置提供的扩展名 2. 模块声明的扩展名 3. 默认扩展名
|
||||
// Priority: 1. Config-provided extensions 2. Module-declared extensions 3. Default extensions
|
||||
let extensionPatterns: string[];
|
||||
if (webConfig.assetExtensions && webConfig.assetExtensions.length > 0) {
|
||||
extensionPatterns = webConfig.assetExtensions;
|
||||
} else {
|
||||
const moduleExtensions = this._collectModuleAssetExtensions(context);
|
||||
const combinedPatterns = new Set([
|
||||
...WebBuildPipeline.DEFAULT_ASSET_EXTENSIONS,
|
||||
...moduleExtensions.patterns
|
||||
]);
|
||||
extensionPatterns = Array.from(combinedPatterns);
|
||||
}
|
||||
|
||||
const assetExtensions = this._globPatternsToExtensions(extensionPatterns);
|
||||
const assetFiles = await fs.listFilesByExtension(assetsDir, assetExtensions, true);
|
||||
|
||||
for (const assetPath of assetFiles) {
|
||||
const ext = assetPath.split('.').pop()?.toLowerCase() || '';
|
||||
const fileName = assetPath.split(/[/\\]/).pop() || '';
|
||||
const ext = fileName.split('.').pop()?.toLowerCase() || '';
|
||||
const relativePath = assetPath.replace(assetsDir, '').replace(/\\/g, '/').replace(/^\//, '');
|
||||
const mimeType = this._getMimeType(ext);
|
||||
|
||||
if (ext === 'json') {
|
||||
// JSON files are read as text
|
||||
// JSON files - check for compound extension types
|
||||
const content = await fs.readFile(assetPath);
|
||||
const assetType = this._getAssetTypeFromFileName(fileName, webConfig, context);
|
||||
assetData[relativePath] = {
|
||||
dataUrl: `data:application/json;base64,${Buffer.from(content).toString('base64')}`,
|
||||
type: 'data'
|
||||
type: assetType
|
||||
};
|
||||
} else {
|
||||
// Binary files
|
||||
const base64 = await fs.readBinaryFileAsBase64(assetPath);
|
||||
assetData[relativePath] = {
|
||||
dataUrl: `data:${mimeType};base64,${base64}`,
|
||||
type: this._getAssetType(ext)
|
||||
type: this._getAssetTypeFromFileName(fileName, webConfig, context)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user