CSharpToJavaScript

CLI github | Dotnet tool | Core github | Nuget package | Try it online!

Features

Web api included by default.

CS:

HTMLElement body = GlobalThis.Window.Document.Body;
HTMLFormElement todoForm = (body as ParentNode).QuerySelector<HTMLFormElement>("#TodoForm");

JS:

let body = globalThis.window.document.body;
let todoForm = body.querySelector("#TodoForm");

ECMA api included by default.

CS:

GlobalThis.Console.Log("Hello");

JS:

globalThis.console.log("Hello");

Special methods to emulate js features.

CS:

Delete(a);

JS:

delete a;

Basic/partial net api translation.

CS:

Console.WeriteLine("Hello");

JS:

console.log("Hello");

Basic "interop" for JS calling.

For example, if you have a JS file located in "./lib/test.js" with an export, you can use ImportAttribute with IgnoreAttribute and ValueAttribute (optionally).

./lib/test.js:

	export function helloWorld() {}

./Program.cs:

	using CSharpToJavaScript.Utils;
	class C
	{
		[Import("helloWorld","../lib/test.js")]
		[Ignore]
		[Value("helloWorld")]
		void HelloWorld(){}
		C() { HelloWorld(); }
	}

The translated file will be:

./Output/Program.js:

	import { helloWorld } from '../lib/test.js';
	class C
	{
		constructor(){ helloWorld(); }
	}

For a slightly more complex example using the node api visit tutorial.

Automatic modules by default.

Can be disabled, see EnableModules. See the tutorial for an example.

Warning

Because translation is happening as-is, there are many (BIG!) limitations.

For example, namespaces are ignored, if you have 2 identical classes but in different namespaces, both will be translated with the same name!

Structs/Interfaces and many more are completely ignored.

The output is not tied to the ECMA standard, meaning if you use a static constructor in cs it will be translated as a static constructor even though it is ECMA 13th.

Quick start for a CLI

To install:

dotnet tool install --global TiLied.CSTOJS_CLI

To use:

cstojs-cli setup "Output"
cstojs-cli translate

To update:

dotnet tool update --global TiLied.CSTOJS_CLI

To uninstall:

dotnet tool uninstall --global TiLied.CSTOJS_CLI

Using as a library

FileData file = new()
{
	SourceStr = @"Console.WriteLine(""Hello world."");"
};
file = CSTOJS.Translate(file);

Console.WriteLine(file.TranslatedStr);
  • Run a program
  • Console output should be:
console.log("Hello world.");