Popularity
4.5
Growing
Activity
7.3
-
634
16
34

Programming language: C#
License: MIT License

DotNetJS alternatives and similar modules

Based on the "Cross-platform integration" category.
Alternatively, view bootsharp alternatives based on common mentions on social networks and blogs.

Do you think we are missing an alternative of DotNetJS or a related project?

Add another 'Cross-platform integration' Module

README

DotNetJS

NuGet CodeFactor codecov CodeQL

The solution provides user-friendly workflow for consuming .NET C# programs and libraries in any JavaScript environment, be it web browsers, Node.js or custom restricted spaces, like web extensions for VS Code, where neither node modules nor browser APIs are available.

The solution is based on two main components:

  • DotNet. Provides JavaScript interoperability layer in C# and packs project output into single-file JavaScript library via MSBuild task. Produced library contains dotnet runtime initialized with the project assemblies and ready to be used as interoperability layer for the packaged C# project. Can optionally emit type definitions to bootstrap TypeScript development.
  • JavaScript. Consumes compiled C# assemblies and .NET runtime WebAssembly module to provide C# interoperability layer in JavaScript. The library is environment-agnostic — it doesn't depend on platform-specific APIs, like browser DOM or node modules and can be imported as CommonJS or ECMAScript module or consumed via script tag in browsers.

Quick Start

In C# project configuration file specify Microsoft.NET.Sdk.BlazorWebAssembly SDK and import DotNetJS NuGet package:


<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">

    <PropertyGroup>
        <TargetFramework>net6.0</TargetFramework>
    </PropertyGroup>

    <ItemGroup>
        <PackageReference Include="DotNetJS" Version="*"/>
    </ItemGroup>

</Project>

To associate a JavaScript function with a C# method use JSFunction attribute. To expose a C# method to JavaScript, use JSInvokable attribute:

using System;
using DotNetJS;
using Microsoft.JSInterop;

namespace HelloWorld;

public partial class Program
{
    // Entry point is invoked by the JavaScript runtime on boot.
    public static void Main ()
    {
        // Invoking 'dotnet.HelloWorld.GetHostName()' JavaScript function.
        var hostName = GetHostName();
        // Writing to JavaScript host console.
        Console.WriteLine($"Hello {hostName}, DotNet here!");
    }

    [JSFunction] // The interoperability code is auto-generated.
    public static partial string GetHostName ();

    [JSInvokable] // The method is invoked from JavaScript.
    public static string GetName () => "DotNet";
}

Publish the project with dotnet publish. A single-file dotnet.js library will be produced under the "bin" directory. Consume the library depending on the environment:

Browser

<!-- Import as a global 'dotnet' object via script tag. -->
<script src="dotnet.js"></script>

<script>

    // Providing implementation for 'GetHostName' function declared in 'HelloWorld' C# assembly.
    dotnet.HelloWorld.GetHostName = () => "Browser";

    window.onload = async function () {
        // Booting the DotNet runtime and invoking entry point.
        await dotnet.boot();
        // Invoking 'GetName()' C# method defined in 'HelloWorld' assembly.
        const guestName = dotnet.HelloWorld.GetName();
        console.log(`Welcome, ${guestName}! Enjoy your global space.`);
    };

</script>

Node.js

// Import as CommonJS module.
const dotnet = require("dotnet");
// ... or as ECMAScript module in node v17 or later.
import dotnet from "dotnet.js";

// Providing implementation for 'GetHostName' function declared in 'HelloWorld' C# assembly.
dotnet.HelloWorld.GetHostName = () => "Node.js";

(async function () {
    // Booting the DotNet runtime and invoking entry point.
    await dotnet.boot();
    // Invoking 'GetName()' C# method defined in 'HelloWorld' assembly.
    const guestName = dotnet.HelloWorld.GetName();
    console.log(`Welcome, ${guestName}! Enjoy your module space.`);
})();

Example Projects

Find the following sample projects in this repository:

  • Hello World — Consume the produced library as a global import in browser, CommonJS or ES module in node.
  • Web Extension — Consume the library in VS Code web extension, which works in both web and standalone versions of the IDE.
  • React — A sample React app, which uses dotnet as backend. Features binaries side-loading and mocking dotnet APIs in unit tests.
  • Runtime Tests — Integration tests featuring various usage scenarios: async method invocations, interop with instances, sending raw byte arrays, streaming, etc.

A real-life usage of the solution can be found in https://github.com/Naninovel/Language. The project is an implementation of language server protocol that is used in VS Code extension: https://github.com/Naninovel/VSCode.

Events

To make a C# method act as event broadcaster for JavaScript consumers, annotate it with [JSEvent] attribute:

[JSEvent]
public static partial string OnSomethingHappened (string payload);

— and consume it from JavaScript as follows:

dotnet.MyApp.OnSomethingHappened.subscribe(handleSomething);
dotnet.MyApp.OnSomethingHappened.unsubscribe(handleSomething);

function handleSomething (payload) {

}

When the method in invoked in C#, subscribed JavaScript handlers will be notified.

In TypeScript the event will have typed generic declaration corresponding to the event arguments.

Sideloading Binaries

By default, DotNetJS build task will embed project's DLLs and .NET WASM runtime to the generated JS library. While convenient and even required in some cases (eg, for VS Code web extensions), this also adds about 30% of extra size due to binary->base64 conversion of the embedded files.

To disable the embedding, set EmbedBinaries build property to false:

<PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <EmbedBinaries>false</EmbedBinaries>
</PropertyGroup>

The dotnet.wasm and solution's assemblies will be emitted in the build output directory. You will then have to provide them when booting:

const bootData = {
    wasm: Uint8Array,
    assemblies: [ { name: "Foo.dll", data: Uint8Array } ],
    entryAssemblyName: "Foo.dll"
};
await dotnet.boot(bootData);

— this way the binary files can be streamed directly from server to optimize traffic and initial load time.

Use getBootUris() function to get identifiers of all the resources required for boot. Below is an example on fetching the boot data; it assumes both wasm and assemblies are stored under /bin directory on the remote server:

async function fetchBootData() {
    const uris = getBootUris();
    return {
        wasm: await fetchBinary(uris.wasm),
        assemblies: await Promise.all(uris.assemblies.map(fetchAssembly)),
        entryAssemblyName: uris.entryAssembly
    };

    async function fetchBinary(name: string) {
        const uri = `${process.env.PUBLIC_URL}/bin/${name}`;
        return new Uint8Array(await (await fetch(uri)).arrayBuffer());
    }

    async function fetchAssembly(name: string) {
        return { name, data: await fetchBinary(name) };
    }
}

Find sideloading example in the React sample. Also, take a look at the build script, which automatically deploys the binaries to the react public directory after building the backend.

Namespace Pattern

By default, all the generated JavaScript binding objects and TypeScript declarations are grouped under corresponding C# namespaces.

To override the generated namespaces, apply JSNamespace attribute to the entry assembly of the C# program. The attribute expects pattern and replacement arguments, which are provided to Regex.Replace when building the generated namespace name.

For example, to transform Company.Product.Space into Space namespace, use the following pattern:

[assembly:JSNamespace(@"Company\.Product\.(\S+)", "$1")]

JSON Serializer Options

To override default JSON serializer options used for marshalling the interop data, use JS.Runtime.ConfigureJson method before the program entry point is invoked. For example, below will add JsonStringEnumConverter converter to allow serializing enums via strings:

static class Program
{
    static Program () // Static constructor is invoked before 'Main'
    {
        JS.Runtime.ConfigureJson(options =>
            options.Converters.Add(new JsonStringEnumConverter())
        );
    }

    public static void Main () { }
}

Compiling Runtime

To compile and test the runtime run the following in order under JavaScript folder:

scripts/install-emsdk.sh
scripts/compile-runtime.sh
npm build
scripts/compile-test.sh
npm test

FAQ

I'm getting "An instance of analyzer Generator.SourceGenerator cannot be created" warning

You are probably using an older .NET SDK. Please download the latest version.