Search code examples
typescriptasp.net-corenugetblazor-webassembly

Use typescript compiler output from .NET library in Blazor app referencing it


I have a problem with three levels:

Bascis: I have a Blazor WASM application that needs some javascript, but I want to use typescript. So I added a tsconfig file and the typescript from the wwwroot folder gets compiled to js and included in the wwwroot output. I can now load it from the WASM running in the browser.

In library: Here is the first problem
I want to move the typescript and surrounding module to its own library project.
I created a new class library project, created a wwwroot folder there, moved the ts file to that wwwroot folder and the tsconfig file to the root of the new library, installed Microsoft.JSInterop in that library, and referenced it from the Blazor app.

Unfortunately, js file isn't included in the app's output and I'm not sure how to continue. Do I have to add a tsconfig to the app? Seems wrong, since the app should just use everything the library provides, the library should be able to provide things without the app having to compile it.

Update:
Initially forgot to add the Microsoft.TypeScript.MSBuild package to the library project. Added that and <TypeScriptCompile Include="wwwroot\myFile.ts" /> (copied from the initial Blazor WASM project), but it says it can't interate over a Uint8Array because it needs at least es2015, which is strange because "target" in the tsconfig.json is es2020 so I guess it doesn't properly map the tsconfig now?

Update 2:
The library has to be created as Razor Class library (.Sdk.Razor), now the ts is compiled to js. I then set its copy property to PreserveNewest, as suggested in the answer linked in the next step. Now the js file is included in the output of the app.
New problem:
Blazor WASM can't load it, gets 404 as response.

Next step: In NuGet package
When this works, I want to distribute the library as NuGet package, so people can install it to their Blazor WebAssembly project, without having to create a tsconfig or the js file.
Another SO answer told the OP to set the js file as "content" in the csproj file and tell nuget to copy that js file to wwwroot of the app on installation. Except I don't have a js file in my library, just the ts file that gets compiled into js output. Where do I tell nuget to copy the js file from?


Solution

  • So after checking even more websites and trying even more stuff than before, I solved it:

    When from a library, the file isn't served under /myFile.js, but under /_content/My.Lib/myFile.js, as are all static files from libraries.
    This same concept also applies if the library is included as NuGet package.