简体   繁体   中英

Minify C3 code in Visual Studio 2017

I want to minify C# codes(files) inside Visual Studio 2017. Is there any extension or other ways to do this. I've searched already and nothing useful was found. I know that there are ways to minify js, CSS or HTML files, but I need minifier for C# if there exist

You can write a class that inherits from the base class CSharpSyntaxRewriter and use it to minify the code based on however it is you wish to minify it.

A starter would be removing all syntax trivia, which can be easily achieved with the following implementation of the CSharpSyntaxRewriter base class:

public class TriviaRemover : CSharpSyntaxRewriter
{
    public override SyntaxNode Visit(SyntaxNode node) => base.Visit(node).WithoutTrivia();

    public override SyntaxTrivia VisitTrivia(SyntaxTrivia trivia) => default;
}

To actually use this, something like the following example would work:

var tree = CSharpSyntaxTree.ParseText(@"
  public class Foo
  {
      //Here some trivia to be removed
      public string bar = ""bar"";
  }");
var Mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
var compilation = CSharpCompilation.Create("MyCompilation",
    syntaxTrees: new[] { tree }, references: new[] { Mscorlib });
var model = compilation.GetSemanticModel(tree);
var root = model.SyntaxTree.GetRoot();

var tr = new TriviaRemover();
var newRoot = tr.Visit(root);

Console.WriteLine(newRoot.GetText());
Console.ReadLine();

Have a look here for another example (where the example code above originated): https://johnkoerner.com/csharp/using-a-csharp-syntax-rewriter/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM