19

Is it possible to compile existing C# code to WebAssembly (.wasm) so that no or nearly no code changes have to be done?
Do I have to use Blazor for it or are their other possibilities?

H H
  • 263,252
  • 30
  • 330
  • 514
Janine
  • 297
  • 3
  • 9
  • 5
    Currently (.NET 5.0), Blazor does not compile your code to WebAssembly. Instead, it uses a .NET runtime, which has been compiled to WebAssembly, that interprets the IL of your code. – pschill Jan 26 '21 at 12:50
  • Thanks a lot, so I can use existing C# code? – Janine Jan 27 '21 at 06:46

2 Answers2

7

Use .NET 7. This support for compiling C# to wasm is now officially added even outside of the Blazor ecosystem.

https://devblogs.microsoft.com/dotnet/use-net-7-from-any-javascript-app-in-net-7/

Full .NET 7 release notes: https://devblogs.microsoft.com/dotnet/announcing-dotnet-7/

While still slightly raw around the edges, this is supposed to get buttoned up and refactored significantly for .NET 8, according to the first comment here.

jjxtra
  • 20,415
  • 16
  • 100
  • 140
  • 1
    I guess with NET8 LTS this will become a reality and super easy to build in pipelines, including Linux nodes, with OUT the need of strange bootstrapping stuff on the host. This should be the new accepted answer – Piotr Kula Dec 14 '22 at 09:52
  • Hopefully they fix the inefficiency of having one js file per .NET assembly, it would be nice to just have one dotnet.js file. – jjxtra Dec 15 '22 at 15:40
5

Is it possible to compile existing C# code to WebAssembly (.wasm)

No, there is no compiler (yet). But

so that no or nearly no code changes have to be done?

That is easy, you can simply add .net DLLs (packages) to your project.
Just make sure that the code makes sense in a Browser, ie no Threading, no I/O except HttpClient etc.

Do I have to use Blazor for it or are their other possibilities?

For now there is only Blazor.

H H
  • 263,252
  • 30
  • 330
  • 514
  • 8
    Well, there is Microsoft's NativeAOT (was CoreRT) https://github.com/dotnet/runtimelab/blob/feature/NativeAOT-LLVM/docs/workflow/building/coreclr/nativeaot.md . Its not an officially supported branch, the community contributes to it with help from Microsoft. It will compile some c# code to Wasm (using emscripten and the LLVM compiler). You can look at the HelloWasm.cs test bucket to get an idea of what should work : https://github.com/dotnet/runtimelab/blob/feature/NativeAOT-LLVM/src/tests/nativeaot/SmokeTests/HelloWasm/HelloWasm.cs – S Waye Jan 30 '21 at 00:40
  • 1
    @SWaye Your answer is closer than the voted answer :) Thank you! – Richard Lalancette Sep 10 '21 at 16:36
  • Sorry -1, since this answer is now out of date and really we should be promoting the latest NET7 / NET8 answers – Piotr Kula Dec 14 '22 at 09:53