#Import .NET8.0 Wasm code in React Vite

1 messages · Page 1 of 1 (latest)

hollow olive
#

Hi,

I am a super newbie, but at least I have tried for 11 hours straight before asking for help, I have tried everything I could. If you could give me precise code or line-by-line steps it would be really appreciated.

Here is what I am doing:

  1. I have a working React+vite project in a Visual Studio solution, working correctly.
  2. I create a new project in my solution, a C# console app
  3. I have installed the wasm-tools
    (this is where I am starting to have no idea of what I am doing...)
  4. I put this in my .csproj, whatever in there is needed :
    `<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<InvariantGlobalization>true</InvariantGlobalization>

<RuntimeIdentifier>browser-wasm</RuntimeIdentifier>
<PublishReadyToRun>false</PublishReadyToRun>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>

</PropertyGroup>

</Project>`

  1. I put the following simple code in my Program.cs:
    `using System;
    using System.Runtime.InteropServices.JavaScript;

namespace MyNamespace
{
public partial class Program
{
[JSExport]
public static int GenerateRandomNumber()
{
Random rnd = new Random();
return rnd.Next(1, 100);
}

    public static void Main()
    {
        Console.WriteLine("WASM Random Number Generator Loaded");
    }
}

}6. I compile the projectwith dotnet publish -c Release`
7. I put MyNamespace.wasm or the full Appbundle generated folder by the build in my react /public folder (I prefer the single file but no idea what is going to work at this point)
8. I create a react component named wasmTemp.jsx with the following code:
import init from '/_framework/MyNamespace.wasm?init';
But nothing works, I have tried many different code below, I have absolutely no idea how to make this work.

Thanks for your help

hollow olive
#

Just in case anybody comes here, through all the chaotic resources on this, I think the good one is this one:
https://learn.microsoft.com/en-us/aspnet/core/client-side/dotnet-interop?view=aspnetcore-8.0

I was also missing this critical line in my build config, you NEED to include an empty / placeholder js file in your setup from what I understand:
<WasmMainJSPath>main.js</WasmMainJSPath>

So I'll go once again through these and I am confident that I should be able to make it work this time with these instructions.