有一个名为 Fantastic Dice 的应用程序,它是一个 javascript 模块。它可以从本页提供的示例中加载。
https://codesandbox.io/p/sandbox/dice-es6-module-cdn-lhbs99?file=%2Fsrc%2Findex.js%3A1%2C1-2%2C1
我尝试在 Blazor 页面中执行此操作,但没有成功。
我有以下名为 dice.js 的 javascript 文件
import DiceBox from "https://unpkg.com/@3d-dice/[email protected]/dist/dice-box.es.min.js";
export function DiceBoxCall() {
let Box = new DiceBox("#dice-box", {
assetPath: "assets/",
origin: "https://unpkg.com/@3d-dice/[email protected]/dist/",
theme: "default",
themeColor: "#feea03",
offscreen: true,
scale: 6
});
Box.init().then(async (world) => {
Box.roll(["4d20", "4d12", "4d10", "4d8", "4d6", "4d4"]);
});
}
我使用 JSRuntime 库从 Blazor 调用它
await JSRuntime.InvokeVoidAsync("DiceBoxCall");
此加载,但找不到 DiceBoxCall。我很确定它是进口,但进口对一切都至关重要。 Fantasy dice 使用的库是 ESModule,导入调用将该库加载到类对象中。我在这里找不到任何其他可以帮助我的例子。
编辑:
我尝试按照以下方式使用,但没有成功。
<HeadContent>
<script type="module">
import DiceBox from "@3d-dice/dice-box"
</script>
</HeadContent>
刚刚尝试了类似于我在这篇文章中描述的方法,它似乎有效。
我有三个文件:
@page "/DiceRoller"
DiceRoller
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
namespace BlazorServerJS.Pages;
public partial class DiceRoller : ComponentBase
{
[Inject]
private IJSRuntime JS { get; set; } = default!;
private IJSObjectReference? _jsModule;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
_jsModule ??= await JS.InvokeAsync(
"import", "./Pages/DiceRoller.razor.js");
await _jsModule.InvokeVoidAsync("DiceBoxCall");
await base.OnAfterRenderAsync(firstRender);
}
}
import DiceBox from "https://unpkg.com/@3d-dice/[email protected]/dist/dice-box.es.min.js";
export function DiceBoxCall() {
let Box = new DiceBox("#dice-box", {
assetPath: "assets/",
origin: "https://unpkg.com/@3d-dice/[email protected]/dist/",
theme: "default",
themeColor: "#feea03",
offscreen: true,
scale: 6
});
Box.init().then(async (world) => {
Box.roll(["4d20", "4d12", "4d10", "4d8", "4d6", "4d4"]);
});
}