TypeWriter扩展生成TS文件时自动导入外部类的问题排查
Let's break down what's going wrong and how to fix it:
1. The Template Method Call Mistake
The biggest issue here is how you're referencing your Imports method in the template. TypeWriter uses $ for built-in variables (like $Name, $Properties), but custom methods require the @ symbol to invoke them.
Your current template uses $Imports, which TypeWriter doesn't recognize as a method call—it just treats it as a literal string. To fix this, replace $Imports with a call to your method, passing the current class and file context:
$Classes(*DTO)[ @Imports(Class, File) export interface $Name { $Properties[ // $LoudName $name: $Type;] } ]
Classrefers to the current class being processed in the$ClassesloopFilerefers to the current C# file being parsed (a global variable in TypeWriter templates)
2. Case Sensitivity Bug in the Imports Method
Looking at your Imports code, you're using lowercase name properties, but TypeWriter's model objects use PascalCase Name properties. This means your check for existing classes in the file will never match, leading to incorrect imports (or missing them entirely).
Here's the corrected method with proper PascalCase:
string Imports(Class c, File f) { IEnumerable<string> classesInFile = f.Classes.Select(p => p.Name); IEnumerable<Type> externalTypes = c.Properties .Select(p => p.Type) .Where(t => ((!t.IsPrimitive || t.IsEnum) && !classesInFile.Contains(t.Name))) .Select(t => t.IsGeneric ? t.TypeArguments.First() : t) .Where(t => t.Name != c.Name && t.Name != "DbGeography") .Distinct(); return string.Join(Environment.NewLine, externalTypes.Select(t => $"import {{ {t.Name} }} from './misc';").Distinct()); }
Key fixes here:
- Changed
p.nametop.Namewhen getting class names from the file - Changed
t.nametot.Namewhen checking if a type exists in the current file
3. Verify the Output
For your example C# class ADTO, this corrected code will generate:
import { BDTO } from './misc'; export interface ADTO { // Id id: number; // EditionId editionId: number; // Mask mask: BDTO; }
Additional Notes
- Ensure your
Importsmethod is defined in the same template file (or in a partial template included with@Include) so TypeWriter can access it - If you work with generic types that have multiple arguments, you may want to adjust the
t.TypeArguments.First()line to handle all arguments, but this works for single-generic use cases like your example
内容的提问来源于stack exchange,提问作者j.her

