Skip to content

TiLied/CSharpToJavaScript

Repository files navigation

CSharpToJavaScript

Nuget package | Website | Try it online! | CLI | VS Code Extension | VS Extension

C# conversion to JavaScript as is.

This is a personal project. Updates will be irregular.

C# input

namespace ConsoleAppTest.CSharp;

public class Test							
{
	public Test()
	{
		Console.WriteLine("Hello World!");
	}
}

Javascript output

class Test
{
	constructor()
	{
		console.log("Hello World!");
	}
}

How to use

CSTOJS cstojs = new();
await cstojs.GenerateOneAsync("Path(full path) to c# file(folder with c# files)");

Other methods "GenerateOne" can be found on the website.

  • 5 Run program and file will be generated in output path(default is "Directory.GetCurrentDirectory()") with name "|C# file name|.js"(default)
  • 6 See below for an example "Model" and "HelloWorld".

Example "Model"

Program.cs

using CSharpToJavaScript;
namespace ConsoleAppTest;

public class Program
{
	public static async Task Main()
	{
		CSTOJS cstojs = new(new CSTOJSOptions() 
			{ 
				KeepBraceOnTheSameLine = true,
				NormalizeWhitespace = true
			});
		await cstojs.GenerateOneAsync("C:\\GitReps\\ConsoleAppTest\\CSharp\\Person.cs");

		Console.ReadKey();
	}
}

List of options can be found on the website or in the code directly.

CSharp/Person.cs

using static CSharpToJavaScript.APIs.JS.GlobalObject;
namespace ConsoleAppTest.CSharp;

public partial class Person
{
    private int _Id;
    public string FullName { get; set; }
    public int Age { get; set; }
}

Above code will generate "Person.js" file that contains:

class Person {
    _Id;
    #_FullName_;
    get FullName() { return this.#_FullName_; } 
    set FullName(value) { this.#_FullName_ = value; }
    #_Age_;
    get Age() { return this.#_Age_; } 
    set Age(value) { this.#_Age_ = value; }
}

Example "HelloWorld"

Program.cs

using CSharpToJavaScript;
namespace ConsoleAppTest;

public class Program
{
	public static async Task Main()
	{
		CSTOJS cstojs = new();
		await cstojs.GenerateOneAsync("C:\\GitReps\\ConsoleAppTest\\CSharp\\Test.cs");

		Console.ReadKey();
	}
}

CSharp/Test.cs

using static CSharpToJavaScript.APIs.JS.GlobalObject;
namespace ConsoleAppTest.CSharp;

public class Test
{
	public Test()
	{
		GlobalThis.Console.Log("HelloWorld!");
	}
}

Above code will generate "Test.js" file that contains:

class Test
{
	constructor()
 	{
   		globalThis.console.log("HelloWorld!");
 	}
}

Related Repository

CLI for library: https://github.com/TiLied/CSTOJS_CLI

VS Code Extension using CLI: https://github.com/TiLied/CSTOJS_VSCode_Ext

VS Extension using CLI: https://github.com/TiLied/CSTOJS_VS_Ext

Website/documentation: https://github.com/TiLied/CSTOJS_Pages

Project includes

Microsoft CodeAnalysis CSharp Core nuget package.

MDN-content for JS api.