单独构建的时候会出现 MIME 问题,采用直接讲 pkg
下的 **.js
文件拆开来放在主要的文件里
看起来就像这样:
async function initWasm() {
const response = await fetch('./pkg/hello_wasm_bg.wasm');
const wasmModule = await WebAssembly.instantiateStreaming(response);
return wasmModule.instance.exports;
}
import { check_flag, __wbg_set_wasm } from './pkg/hello_wasm_bg.js';
async function main() {
try {
const wasm = await initWasm();
__wbg_set_wasm(wasm);
const button = document.getElementById("submit");
button.addEventListener("click", () => {
// 获取输入的 flag
const flag = document.getElementById("input").value;
// 调用 WebAssembly 模块中的函数
if (check_flag(flag)) {
alert("Flag is correct!");
} else {
alert("Flag is incorrect!");
}
});
} catch (error) {
console.error("Error loading WebAssembly module:", error);
}
}
main().catch(console.error);