3.2 编写自定义导入器
导入器分探测与导入两步:探测只回答能不能处理,导入才产出产物。管线按注册顺序询问探测,第一个命中者执行;结果带上导入器 id 与版本,写进资产 meta,后续版本升级时据此判断要不要重新导入。
本章与站内既有内容的分工
| 主题 | 站内既有内容 | 本节做什么 |
|---|---|---|
| 导入器框架 | 《资产管线》 第 3 章 | 卷二实现内置导入器与优先级;本节补第三方导入器契约 |
| 资产数据库 | 《资产管线》 第 2 章 | 数据库记录导入结果;本节保证结果可追溯到导入器版本 |
| 全卷脉络 | 本卷目录 | 本节承接 3.1 的类型声明 |
从零实现:编写自定义导入器
管线维护有序导入器列表,重复 id 拒绝注册。run 按顺序调用 detect,没有命中就抛出带路径的错误;命中后调用 import,把产物与警告复制进结果,并记录导入器 id 与版本。复制产物避免调用方修改导入器内部缓存。
对标导入扩展
Unity 的 ScriptedImporter 通过 OnImportAsset 接收导入上下文,可登记生成对象并指定主对象。helio 模型按探测结果选择导入器,并在输出中保留来源与诊断。 Unity ScriptedImporter
可运行产物:6 条用例
下面是 src/importer-pipeline.ts,层级 L1,完整可编译。运行命令 node --test test/03-2-write-custom-importer.test.ts:
// file: src/importer-pipeline.ts
// tier: L1
// verify: node --test test/03-2-write-custom-importer.test.ts
//
// 卷四(第三章):编写自定义导入器。
// 导入器分探测与导入两步:探测只回答「我能不能处理」,导入才产出产物。
// 管线按注册顺序询问探测,第一个命中者执行;结果带上导入器 id 与版本,
// 写进资产 meta,后续版本升级时据此判断要不要重导。
export interface ImportSource {
path: string;
kind: string;
}
export interface ImportArtifact {
path: string;
bytes: number;
}
export interface ImportOutput {
artifacts: ImportArtifact[];
warnings?: string[];
}
export interface Importer {
id: string;
version: string;
detect(source: ImportSource): boolean;
import(source: ImportSource): ImportOutput;
}
export interface ImportResult {
importerId: string;
version: string;
artifacts: ImportArtifact[];
warnings: string[];
}
export class ImporterPipeline {
#importers: Importer[] = [];
add(importer: Importer): void {
if (this.#importers.some((i) => i.id === importer.id)) {
throw new Error(`导入器 ${importer.id} 已注册`);
}
this.#importers.push(importer);
}
run(source: ImportSource): ImportResult {
const importer = this.#importers.find((i) => i.detect(source));
if (!importer) {
throw new Error(`没有导入器能处理 ${source.path}`);
}
const output = importer.import(source);
return {
importerId: importer.id,
version: importer.version,
artifacts: output.artifacts.map((a) => ({ ...a })),
warnings: [...(output.warnings ?? [])],
};
}
count(): number {
return this.#importers.length;
}
}
探测顺序就是优先级:先注册的导入器先有机会处理。真实系统里通常把专用导入器放在通用导入器之前,所以注册顺序本身是一种策略声明。产物与警告都做浅拷贝,避免管线外部持有导入器内部状态。
下面是 test/03-2-write-custom-importer.test.ts,层级 L1:
// file: test/03-2-write-custom-importer.test.ts
// tier: L1
// verify: node --test test/03-2-write-custom-importer.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { ImporterPipeline } from '../src/importer-pipeline.ts';
const imageImporter = {
id: 'image',
version: '1.2.0',
detect: (s: { path: string }) => s.path.endsWith('.png'),
import: (s: { path: string }) => ({
artifacts: [{ path: `${s.path}.tex`, bytes: 1024 }],
warnings: ['使用默认压缩'],
}),
};
const textImporter = {
id: 'text',
version: '1.0.0',
detect: (s: { path: string }) => s.path.endsWith('.json'),
import: (s: { path: string }) => ({ artifacts: [{ path: `${s.path}.bin`, bytes: 64 }] }),
};
test('首个探测命中的导入器执行', () => {
const p = new ImporterPipeline();
p.add(textImporter);
p.add(imageImporter);
const result = p.run({ path: 'boat.png', kind: 'texture' });
assert.equal(result.importerId, 'image');
});
test('按注册顺序探测', () => {
const p = new ImporterPipeline();
const first = { ...imageImporter, id: 'first' };
const second = { ...imageImporter, id: 'second' };
p.add(first);
p.add(second);
assert.equal(p.run({ path: 'a.png', kind: 'texture' }).importerId, 'first');
});
test('没有导入器命中时报错', () => {
const p = new ImporterPipeline();
p.add(imageImporter);
assert.throws(() => p.run({ path: 'a.fbx', kind: 'mesh' }), /没有导入器能处理/);
});
test('结果携带导入器版本与警告', () => {
const p = new ImporterPipeline();
p.add(imageImporter);
const result = p.run({ path: 'a.png', kind: 'texture' });
assert.equal(result.version, '1.2.0');
assert.deepEqual(result.warnings, ['使用默认压缩']);
});
test('重复导入器 id 报错', () => {
const p = new ImporterPipeline();
p.add(imageImporter);
assert.throws(() => p.add(imageImporter), /已注册/);
assert.equal(p.count(), 1);
});
test('相同输入产生相同产物', () => {
const p = new ImporterPipeline();
p.add(imageImporter);
const a = p.run({ path: 'a.png', kind: 'texture' });
const b = p.run({ path: 'a.png', kind: 'texture' });
assert.deepEqual(a.artifacts, b.artifacts);
});
本机实测(Node v26.5.0,node --test test/03-2-write-custom-importer.test.ts):tests 6 · pass 6 · fail 0,耗时约 40 ms。
前两条钉首个命中和注册顺序;第三条钉无命中报错;第四条钉版本与警告;后两条钉重复 id 与幂等。
小结
- 导入器契约只有 detect 与 import 两个方法。
- 探测顺序即优先级,专用导入器应先注册。
- 结果记录导入器版本,为增量重导提供依据。
- 产物与警告复制后再返回,避免共享内部状态。
阅读导航:上一节:3.1 声明自定义资产类型 · 下一节:3.3 导入器的插件分发 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。