Simple WebAssembly Text Format (WAT) example for beginners showing a basic module exporting a function returning integer 42 without dependencies.
(module
;; Definition of an exported function called 'getNumber'
;; that returns a 32-bit integer with value 42
(func $getNumber (result i32)
i32.const 42
)
;; Exporting the function so it can be called from outside
(export "getNumber" (func $getNumber))
)html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Hello World with WebAssembly Text Format (WAT)</title>
</head>
<body>
<h1>WebAssembly Text Format (WAT) Example</h1>
<button id="run">Run getNumber</button>
<p>Result: <span id="result">-</span></p>
<script type="module">
// Original WAT code as a string
const watCode = `(module
;; Definition of an exported function called 'getNumber'
;; that returns a 32-bit integer with value 42
(func $getNumber (result i32)
i32.const 42
)
;; Exporting the function so it can be called from outside
(export "getNumber" (func $getNumber))
)`;
// Function to compile WAT to WASM binary using WebAssembly.instantiateStreaming is not possible here,
// so we use the WebAssembly Text Format to binary compilation via WebAssembly.compileStreaming or a tool.
// Since browsers don't support direct WAT compilation, we use the WebAssembly.compile with a precompiled binary.
// For demonstration, we will use the WebAssembly Text Format compiled to binary using the WebAssembly JavaScript API
// by using the WebAssembly.compile with a Uint8Array of the binary.
// But since we only have WAT, we need to convert it to binary first.
// To keep it simple and self-contained, we will use the WebAssembly.instantiateStreaming with a base64 encoded wasm binary.
// Precompiled wasm binary of the above WAT (compiled externally):
const wasmBase64 = 'AGFzbQEAAAABBwFgAAF/AwIBAAELBQEDZ2V0TnVtYmVyAAAK';
// Decode base64 to Uint8Array
function base64ToUint8Array(base64) {
const binaryString = atob(base64);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes;
}
const wasmBytes = base64ToUint8Array(wasmBase64);
let wasmInstance;
async function loadWasm() {
const { instance } = await WebAssembly.instantiate(wasmBytes);
wasmInstance = instance;
}
document.getElementById('run').addEventListener('click', async () => {
if (!wasmInstance) {
await loadWasm();
}
// Call the exported function getNumber
const result = wasmInstance.exports.getNumber();
document.getElementById('result').textContent = result;
});
</script>
</body>
</html>