使用vite webassembly 功能简化tinygo webassembly 初始化
vite 对于webassembly 的加载支持url 模式以及init 模式,init 模式可以自动帮助我们生成wasm文件加载的处理代码
比较方便,可以用来替换自己编写的工具类,以下是一个参考使用
参考使用
- index.js
import init from './main.wasm?init'
const go = new Go(); // Defined in wasm_exec.js. Don't forget to add this in your index.html.
const runWasmAdd = async () => {
// Get the importObject from the go instance.
const importObject = go.importObject;
// Instantiate our wasm module, 同时可以传递依赖的importObject
const wasmModule = await init(importObject);
console.log(wasmModule)
// Allow the wasm_exec go instance, bootstrap and execute our wasm module
go.run(wasmModule);
// Call the Add function export from wasm, save the result
const addResult = wasmModule.exports.add(2433, 24);
const printName = wasmModule.exports.printName();
// Set the result onto the body
document.body.textContent = `Hello World! addResult: ${addResult} -- printName: ${printName}`;
};
runWasmAdd();
说明
完整代码已经放到github 了,可以参考
参考资料
https://vitejs.dev/guide/features.html#webassembly
https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface/instantiate
https://github.com/rongfengliang/tinygo-wasm-learning/blob/v2/index.js