I'm writing a Razor Class Library that incorporates JavaScript interop transpiled from TypeScript. Some code in TypeScript will reference globally available variable DotNet which gets included when Blazor libraries are initialized. I was able to find DotNet module declaration in @microsoft/dotnet-js-interop Node package (added as devDependency) and TypeScript is able to find the export when "moduleResolution": "node" is set in my tsconfig.json. However, if I do import { DotNet } from "@microsoft/dotnet-js-interop", then this import is kept in transpiled JavaScript code. I tried a few workarounds, but they didn't work:
import type { DotNet } from "@microsoft/dotnet-js-interop" results in (TS) 'DotNet' cannot be used as a value because it was imported using 'import type'. wherever DotNet is being referenced;///<reference types/path="@microsoft/dotnet-js-interop or node_modules/@microsoft/dotnet-js-interop/dist/Microsoft.JSInterpop.d.ts"> or modifying tsconfig.json values such as paths (with "baseUrl"=".") or typeRoots. All theses result in error (TS) Cannot find name 'DotNet'.Is there any way to properly import DotNet module declaration without polluting transpiled JavaScript code with unnecessary imports?
It was tricky (lack of cohesive documentation didn't help), but I was able to figure it out myself.
The trick is to declare a variable and define its type with typeof import like so:
declare const DotNet: typeof import("@microsoft/dotnet-js-interop").DotNet;
Put this at the top of a file and you're good to go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With