Para compilar C# en WebAssemly e interoperar con JS, es necesario usar el marco Blazor WebAssembly ASP.NET, que está diseñado para SPA y contiene muchos gastos generales en caso de que solo desee usar una biblioteca C# de JS.
¿Cuál es la configuración mínima para compilar una DLL en WebAssembly y usarla desde JavaScript?
Cree un nuevo proyecto de C# vacío con la siguiente configuración (a través de .csproj):
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly"> <PropertyGroup> <TargetFramework>net6.0</TargetFramework> <LangVersion>10</LangVersion> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="6.0.0" /> <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="6.0.0" PrivateAssets="all" /> </ItemGroup> </Project>Inicialice el tiempo de ejecución de Blazor JS y especifique los enlaces:
namespace WasmTest; public class Program { private static IJSRuntime js; private static async Task Main (string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); var host = builder.Build(); js = host.Services.GetRequiredService<IJSRuntime>(); await host.RunAsync(); } [JSInvokable] public static async Task<string> BuildMessage (string name) { var time = await GetTimeViaJS(); return $"Hello {name}! Current time is {time}."; } public static async Task<DateTime> GetTimeViaJS () { return await js.InvokeAsync<DateTime>("getTime"); } } Publique con dotnet publish y use la biblioteca C# de JS:
<script src="_framework/blazor.webassembly.js" autostart="false"></script> <script> window.getTime = () => { return new Date().toJSON(); }; window.onload = async function () { await Blazor.start(); const msg = await DotNet.invokeMethodAsync("WasmTest", "BuildMessage", "John"); console.log(msg); }; </script>Alternativamente, aquí hay una solución que permite compilar el proyecto C# en una biblioteca UMD de un solo archivo, que se puede consumir en cualquier entorno de JavaScript: navegadores, nodos y entornos restringidos personalizados, como las extensiones web de VS Code: https://github. com/Elringus/DotNetJS