Create WebAssembly modules using template strings
You can install watpl using npm:
npm install --save watpl
If you aren't using npm in your project, you can include watpl using UMD build in the dist folder with <script>
tag.
Once you have installed watpl, supposing a CommonJS environment, you can import and use it in this way:
import watpl from "watpl";
(async () => {
// create a template
const createAddModule = watpl`
(module
(func (param $lhs i32) (param $rhs i32) (result i32)
get_local $lhs
i32.const ${options => options.number}
i32.add)
(export "run" (func 0))
)
`;
// create a module that adds 2
const add2 = createAddModule({
number: 2
});
// instantiate and run the module
const instance = await add2.instantiate();
instance.exports.run(3); // 5 = 3 + 2
})();
type WasmModule = {
// created module as string
string: string,
// created module as buffer
buffer: ArrayBuffer,
// created WebAssembly module
module: Promise<WebAssembly.Module>,
// instantiate the module with the given importObject
instantiate: (importObject: Object) => Promise<WebAssembly.Instance>,
// cleanup the module
destroy: () => void,
toString: () => string
};
watpl`
wat code
`: (options: any) => WasmModule
watpl
uses WebAssembly APIs, they are broadly supported by major browser engines but you would like to polyfill them to support old versions.
if (typeof WebAssembly === 'undefined') {
...
} else {
...
}
This project is inspired by this tweet of @rhmoller.
This project adheres to Semantic Versioning.
Every release, along with the migration instructions, is documented on the Github Releases page.
Matteo Basso
Copyright (c) 2019, Matteo Basso.
watpl source code is licensed under the MIT License.