jburzynski / TypeGen

Single-class-per-file C# to TypeScript generator
MIT License
195 stars 55 forks source link

Preserving Directory and Sub-directory Structure in Generated TypeScript Files #169

Open raptyk opened 1 year ago

raptyk commented 1 year ago

Hello,

I'm using typegen for generating TypeScript types from my .NET sources. I was wondering if there is a way to preserve the directory and sub-directory structure of the original .NET source files in the generated TypeScript output. In other words, can the organization of the source files in .NET be replicated in the TypeScript results?

For example: \Dto\Common\User\UserDto.cs --> \Typescript\Common\User\UserDto.ts

For now, the only way I know is to use an attribute in every single cs class file:

[ExportTsClass(OutputDir = @"Typescript\Common\User")].
public class UserDto

Thank you in advance for any guidance!

jburzynski commented 1 year ago

Hi,

there is no built-in way that would allow to do this.

The easiest would probably be to use generation specs which allow to write any logic in C# to automate adding types to generate.

I'm not sure if there is any way to achieve this easily with attributes - at least without using any 3rd party tools.

florisdipt commented 1 year ago

I wanted something similar and solved it this way in the generation spec Hope this helps someone

    private Type[] generateForTypes = {
        typeof(MyWonderfulDto),
        etc...
    };

    private const string RootNameSpaceForFiles = "My.WonderFul.NameSpace";
    public override void OnBeforeGeneration(OnBeforeGenerationArgs args)
    {
        foreach (Type type in generateForTypes)
        {
            string outputDir = null;

            if (type.Namespace != null && type.Namespace.StartsWith(RootNameSpaceForFiles))
            {
                outputDir = type.Namespace;
                outputDir = outputDir.Replace(RootNameSpaceForFiles, "");
                outputDir = outputDir.Replace(".", "/");
                outputDir = $".{outputDir}";
            }

            Console.WriteLine($"outputDir: {outputDir}");

            AddClass(type, outputDir:outputDir);
        }
    }