elringus / bootsharp

Compile C# solution into single-file ES module with auto-generated JavaScript bindings and type definitions
https://bootsharp.com
MIT License
667 stars 36 forks source link

Error running HelloWorld example #7

Closed arjunt24 closed 2 years ago

arjunt24 commented 2 years ago

Hi, thank you so much for creating this helpful project! I am trying to implement the simple HelloWorld example from the ReadMe in my Typescript project, and I'm getting an error. Here are the relevant files:

HelloWorld.cs:

using System;
using DotNetJS;
using Microsoft.JSInterop;

namespace HelloWorld
{

    class Program
    {
        public static void Main ()
        {
            var hostName = JS.Invoke<string>("GetName");
            Console.WriteLine($"Hello {hostName}, DotNet here!");
        }

        [JSInvokable]
        public static string GetName () => "DotNet";
    }
}

HelloWorld.csproj:

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

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

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

</Project>

MyTsFunction:

function myTsFunction(): string {
    const dotnet = require("./bin/dotnet");

    dotnet.HelloWorld.GetHostName = () => "Node.js";

    (async function () {
        await dotnet.boot();

        const guestName = dotnet.HelloWorld.GetName();
        console.log(`Welcome, ${guestName}! Enjoy your module space.`);
    })();

    return "";
}

I ran dotnet publish to create the dotnet.js file and I am able to import the module, but there is an error on the " dotnet.HelloWorld.GetHostName = () => "Node.js"; " line:

Cannot set properties of undefined (setting 'GetName')

Do you have any ideas on how I could fix this?

elringus commented 2 years ago

Hi, Check the web extension sample, it consumes the library in TypeScript.

arjunt24 commented 2 years ago

Thanks for the response. I checked the web extension sample, but it has the same line that is breaking for me ("dotnet.HelloWorld.GetHostName = () => "VS Code""). When I debug it, the "dotnet" object doesn't have a "HelloWorld" property, which is why "dotnet.HelloWorld.GetHostName" is breaking.

elringus commented 2 years ago

Do you have emit types enabled in the project config?

arjunt24 commented 2 years ago

I didn't, but I added it and rebuilt the project and am still getting the same error.

elringus commented 2 years ago

Well, it's working on my end. You're probably missing something. Try cloning the repo and follow the sample instructions closely.

arjunt24 commented 2 years ago

There was an issue with the formatting of my C# file, it works now that I fixed that. Thanks for your help!