我正在尝试创建一个Razor Class Library
,它公开了1个js函数。我的问题是webpack在最终的bundle文件中删除了我导出的函数
index.js
import * as myLib from "someLib"
export function connect(params) {
// function logic omitted for clarity
}
这就是我想要使用js代码的方式
using MyComponent.Common;
using Microsoft.JSInterop;
namespace MyComponent.Services
{
/// <inheritdoc />
public class MyService : IMyService
{
private readonly Lazy<Task<IJSObjectReference>> _myWrapper;
public MyService(IJSRuntime jsRuntime)
{
_myWrapper = new Lazy<Task<IJSObjectReference>>(() =>
jsRuntime.InvokeAsync<IJSObjectReference>("import", "./_content/MyComponent/index.bundle.js")
.AsTask());
}
/// <inheritdoc />
public async Task Connect(params)
{
if (_myWrapper is null)
{
throw new InvalidOperationException("Wrapper is not initialized");
}
IJSObjectReference module = await _myWrapper.Value;
await module.InvokeVoidAsync("connect", params);
}
}
}
我得到的异常是(正如预期的那样,因为在index.bundle.js中没有公开连接函数(
Could not find 'connect' ('connect' was undefined).
Error: Could not find 'connect' ('connect' was undefined).
at https://localhost:7134/_framework/blazor.webassembly.js:1:328
at Array.forEach (<anonymous>)
at a.findFunction (https://localhost:7134/_framework/blazor.webassembly.js:1:296)
at _ (https://localhost:7134/_framework/blazor.webassembly.js:1:2437)
at https://localhost:7134/_framework/blazor.webassembly.js:1:3325
at new Promise (<anonymous>)
at Object.beginInvokeJSFromDotNet (https://localhost:7134/_framework/blazor.webassembly.js:1:3306)
at Object.St [as invokeJSFromDotNet] (https://localhost:7134/_framework/blazor.webassembly.js:1:59849)
at _mono_wasm_invoke_js_blazor (https://localhost:7134/_framework/dotnet.6.0.2-mauipre.1.22102.15.kf8l5pkaed.js:1:194973)
at wasm://wasm/00970ba6:wasm-function[219]:0x1a129
我刚刚找到了解决这个问题的方法。在index.js
的末尾,我插入了以下行
window.connect = connect;
这使得webpack不删除连接函数,但它仍然不能通过IJSObjectReference
使用,因为它希望函数像export function connect
一样导出,所以我在最终index.bundle.js
的末尾插入了另一行
export function connect(params) { window.connect(params); }
我还必须禁用csproj文件上的自动webpack构建,因为每次构建后我的修改都会丢失,仅此而已,之后我就可以很好地使用我的功能了。