DotNetJS 0.20.0

Suggested Alternatives

Bootsharp

There is a newer version of this package available.
See the version list below for details.
dotnet add package DotNetJS --version 0.20.0                
NuGet\Install-Package DotNetJS -Version 0.20.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="DotNetJS" Version="0.20.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add DotNetJS --version 0.20.0                
#r "nuget: DotNetJS, 0.20.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install DotNetJS as a Cake Addin
#addin nuget:?package=DotNetJS&version=0.20.0

// Install DotNetJS as a Cake Tool
#tool nuget:?package=DotNetJS&version=0.20.0                

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.

alternate text is missing from this package README image

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


<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.

React Event Hooks

Below are some utility hooks, which you can use in React to bootstrap usage of the events:

import { DependencyList, useEffect, useState } from "react";
import { EventSubscriber } from "backend";

export function useEvent<T extends any[]>(
    event: EventSubscriber<T>, handler: (...args: [...T]) => void,
    deps?: DependencyList | undefined, destructor?: () => void) {
    useEffect(() => {
        event.subscribe(handler);
        return () => {
            event.unsubscribe(handler);
            destructor?.();
        };
    }, deps);
}

export function useEventState<T extends any[]>(
    event: EventSubscriber<T>,
    defaultState?: T[0]): T[0] | undefined {
    const last = event.getLast();
    const initialState = last === undefined ? defaultState : last[0];
    const [state, setState] = useState<T[0]>(initialState);
    useEvent<T[0]>(event, setState, []);
    return state;
}

The useEventState hook will take care of both subscribing and unsubscribing from the dotnet event when component unmounts and using last event args as the default state to catch up in case the component missed a broadcast before being mounted.

const MyComponent = () => {
    const myData = useEventState(Backend.OnDataChanged);
    return <>{myData}</>;
};

Auto-generating Bindings by Interfaces

Instead of writing a binding for each method, make DotNetJS generate them automatically with [JSImport] and [JSExport] assembly attributes.

For example, let's say we have a JS frontend, which needs to be notified when a data is mutated on our C# backend, so it can render the updated state; additionally, our frontend may have a setting (eg, stored in browser cache) to temporary mute notifications, which needs to be retrieved by the backend. Create the following interface in C# to describe the expected frontend APIs:

interface IFrontend
{
    void NotifyDataChanged (Data data);
    bool IsMuted ();
}

Now add the interface type to the JS import list:

[assembly: JSImport(new[] { typeof(IFrontend) })]

DotNetJS will generate the following C# implementation:

public class JSFrontend : IFrontend
{
    [JSFunction] public static void NotifyDataChanged (Data data) => JS.Invoke("dotnet.Frontend.NotifyDataChanged.broadcast", new object[] { data });
    [JSFunction] public static bool IsMuted () => JS.Invoke<bool>("dotnet.Frontend.IsMuted");

    void IFrontend.NotifyDataChanged (Data data) => NotifyDataChanged(data);
    bool IFrontend.IsMuted () => IsMuted();

}

— which you can use in C# to interop with the frontend and following TypeScript spec to be implemented on the frontend:

export namespace Frontend {
    export const NotifyDataChanged: Event<[Data]>;
    export let IsMuted: () => boolean;
}

Now let's say we want to provide an API for frontend to request mutation of the data:

interface IBackend
{
    void AddData (Data data);
}

Export the interface to JS:

[assembly: JSExport(new[] { typeof(IBackend) })]

Get the following implementation auto-generated:

public class JSBackend
{
    private static IBackend handler = null!;

    public JSBackend (IBackend handler)
    {
        JSBackend.handler = handler;
    }

    [JSInvokable] public static void AddData (Data data) => handler.AddData(data);
}

— which will as well produce following spec to be consumed on JS side:

export namespace Backend {
    export function AddData(data: Data): void;
}

Find example on using the attributes in the React sample.

Overriding Bindings

Both export and import attributes have additional parameters allowing to override generated binding methods names and invocation bodies.

Let's say we want to rename methods starting with Notify... to On... on the JS side to make it more clear that we are notifying on C# side and consuming events on JS:

[assembly: JSImport(new[] {
    ...
}, namePattern: "Notify(.+)", nameReplacement: "On$1")]

Or maybe we want to wrap the exported bindings with some kind of error-catching mechanism:

[assembly: JSExport(new[] {
    ...
}, invokePattern: "(.+)", invokeReplacement: "Try(() => $1)")]

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.

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on DotNetJS:

Package Downloads
Plotly.WPF

Plotly.js in a WPF Control

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
0.23.4 1,783 5/14/2023 0.23.4 is deprecated because it is no longer maintained.
0.23.3 870 2/21/2023 0.23.3 is deprecated because it is no longer maintained.
0.23.2 287 2/21/2023 0.23.2 is deprecated because it is no longer maintained.
0.23.1 551 1/27/2023 0.23.1 is deprecated because it is no longer maintained.
0.23.0 343 1/27/2023 0.23.0 is deprecated because it is no longer maintained.
0.22.0 451 1/21/2023 0.22.0 is deprecated because it is no longer maintained.
0.21.1 381 12/23/2022 0.21.1 is deprecated because it is no longer maintained.
0.21.0 461 12/5/2022 0.21.0 is deprecated because it is no longer maintained.
0.20.0 401 12/4/2022 0.20.0 is deprecated because it is no longer maintained.
0.19.0 393 11/24/2022 0.19.0 is deprecated because it is no longer maintained.
0.18.0 827 11/20/2022 0.18.0 is deprecated because it is no longer maintained.
0.17.1 528 10/15/2022 0.17.1 is deprecated because it is no longer maintained.
0.17.0 479 10/10/2022 0.17.0 is deprecated because it is no longer maintained.
0.16.0 553 10/1/2022 0.16.0 is deprecated because it is no longer maintained.
0.15.1 499 9/1/2022 0.15.1 is deprecated because it is no longer maintained.
0.15.0 553 8/24/2022 0.15.0 is deprecated because it is no longer maintained.
0.14.0 598 7/1/2022 0.14.0 is deprecated because it is no longer maintained.
0.13.8 573 6/6/2022 0.13.8 is deprecated because it is no longer maintained.
0.13.7 454 6/4/2022 0.13.7 is deprecated because it is no longer maintained.
0.13.5 452 6/4/2022 0.13.5 is deprecated because it is no longer maintained.
0.13.4 479 6/4/2022 0.13.4 is deprecated because it is no longer maintained.
0.13.3 443 6/3/2022 0.13.3 is deprecated because it is no longer maintained.
0.13.2 479 5/24/2022 0.13.2 is deprecated because it is no longer maintained.
0.13.1 490 5/23/2022 0.13.1 is deprecated because it is no longer maintained.
0.13.0 488 5/22/2022 0.13.0 is deprecated because it is no longer maintained.
0.12.0 486 5/21/2022 0.12.0 is deprecated because it is no longer maintained.
0.11.0 505 5/21/2022 0.11.0 is deprecated because it is no longer maintained.
0.10.1 465 5/19/2022 0.10.1 is deprecated because it is no longer maintained.
0.10.0 545 5/1/2022 0.10.0 is deprecated because it is no longer maintained.
0.9.2 462 4/29/2022 0.9.2 is deprecated because it is no longer maintained.
0.9.1 490 4/17/2022 0.9.1 is deprecated because it is no longer maintained.
0.9.0 460 4/8/2022 0.9.0 is deprecated because it is no longer maintained.
0.8.2 524 3/22/2022 0.8.2 is deprecated because it is no longer maintained.
0.8.1 474 3/9/2022 0.8.1 is deprecated because it is no longer maintained.
0.8.0 487 2/20/2022 0.8.0 is deprecated because it is no longer maintained.
0.7.3 627 2/16/2022 0.7.3 is deprecated because it is no longer maintained.
0.6.3 516 2/12/2022 0.6.3 is deprecated because it is no longer maintained.
0.6.2 496 2/9/2022 0.6.2 is deprecated because it is no longer maintained.
0.5.4 493 2/8/2022 0.5.4 is deprecated because it is no longer maintained.
0.5.3 601 2/1/2022 0.5.3 is deprecated because it is no longer maintained.
0.5.2 527 1/17/2022 0.5.2 is deprecated because it is no longer maintained.
0.5.1 484 1/13/2022 0.5.1 is deprecated because it is no longer maintained.
0.5.0 513 1/13/2022 0.5.0 is deprecated because it is no longer maintained.
0.4.1 352 1/10/2022 0.4.1 is deprecated because it is no longer maintained.
0.4.0 358 12/24/2021 0.4.0 is deprecated because it is no longer maintained.
0.3.13 336 12/23/2021 0.3.13 is deprecated because it is no longer maintained.
0.3.12 654 12/4/2021 0.3.12 is deprecated because it is no longer maintained.
0.3.11 923 12/1/2021 0.3.11 is deprecated because it is no longer maintained.
0.3.8 366 11/30/2021 0.3.8 is deprecated because it is no longer maintained.
0.2.5 889 11/21/2021 0.2.5 is deprecated because it is no longer maintained.
0.2.0 498 11/19/2021 0.2.0 is deprecated because it is no longer maintained.
0.1.0 374 11/18/2021 0.1.0 is deprecated because it is no longer maintained.