是否可以将导出的 JavaScript 模块 Class 作为 Blazor 中的互操作 Class 导入?

Is it Possible to Import an Exported JavaScript Module Class as Interop Class in Blazor?

在最新 Visual Studio 2019 年为我的 Blazor 服务器端解决方案创建 Razor Class 库时,我看到以下文件:

ExampleJsInterop.cs

    public class ExampleJsInterop : IAsyncDisposable
    {
        private readonly Lazy<Task<IJSObjectReference>> moduleTask;

        public ExampleJsInterop(IJSRuntime jsRuntime)
        {
            moduleTask = new(() => jsRuntime.InvokeAsync<IJSObjectReference>(
               "import", "./_content/MyNamespace/exampleJsInterop.js").AsTask());
        }

        public async ValueTask<string> Prompt(string message)
        {
            var module = await moduleTask.Value;
            return await module.InvokeAsync<string>("showPrompt", message);
        }

        public async ValueTask DisposeAsync()
        {
            if (moduleTask.IsValueCreated)
            {
                var module = await moduleTask.Value;
                await module.DisposeAsync();
            }
        }
    }

exampleJsInterop.js

// This is a JavaScript module that is loaded on demand. It can export any number of
// functions, and may import other JavaScript modules if required.

export function showPrompt(message) {
  return prompt(message, 'Type anything here');
}

这很有趣。但是,我想做的是 use classes instead. I do not see any reference to this in any links that I have searched, and the closest Whosebug question I have found is this one.

是否可以在 JavaScript/browser 中导出 类,然后通过互操作将它们导入 Blazor?如果是,怎么做?

我所做的是在 wwwroot 之外的文件夹中使用这样的 TypeScript class(伪代码),并将 tsconfig 设置为在 Class 库中编译为 wwwroot:

class SizeHelpers {
    public GetBoundingClientRect(element: HTMLElement): DOMRect {
        return element.getBoundingClientRect();
    }
}

然后使用它导出它(在同一个文件中):

export function getSizeHelpers(): SizeHelpers {
    return new SizeHelpers();
}

然后在 C# 中,我在服务中按需导入此文件:

    var helpersInstance = await helpersModule.InvokeAsync<IJSObjectReference>("getSizeHelpers");
    Helpers = new Helpers(helpersInstance);

然后在 C# 中我这样做是为了使用函数:

 public class SizeHelpers
    {
        private readonly IJSObjectReference _instance;

        public SizeHelpers(IJSObjectReference instance)
        {
            _instance = instance;
        }

        public ValueTask<BoundingClientRectangle> GetBoundingClientRect(ElementReference element)
        {
            return _instance.InvokeAsync<BoundingClientRectangle>("GetBoundingClientRect", element);
        }
}