WebAssembly - Convert WAT to WASM

In the previous chapter, we have seen how to write code in .wat i.e., WebAssembly text format. The WebAssembly text format will not directly work inside the browser and you need to convert it into binary format i.e., WASM to work inside browser.


Let us convert .WAT to .WASM.

The code we are going to use is as follows −

   (func $add (param $a i32) (param $b i32) (result i32) 
      get_local $a 
      get_local $b 
   (export "add" (func $add)) 

Now, go to WebAssembly Studio, which is available at https://webassembly.studio/.

You should see something like this, when you hit the link −

Convert WAT to WASM

Click on Empty Wat project and click on Create button at the bottom.

Empty Wat Project

It will take you to an empty project as shown below −

Empty Project

Click on main.wat and replace the existing code with yours and click on the save button.

Existing Code

Once saved, click on the build to convert to .wasm −

Convert to WASM

If the build is successful you should see .wasm file created as shown below −


Down the main.wasm file and use it inside your .html file to see the output as shown below.

For Example − add.html

<!doctype html>
      <meta charset="utf-8">
      <title>WebAssembly Add Function</title>
         let sum; 
            .then(bytes => bytes.arrayBuffer()) 
            .then(mod => WebAssembly.compile(mod)) .then(module => {
            return new WebAssembly.Instance(module) 
         .then(instance => {
            sum = instance.exports.add(10,40); 
            console.log("The sum of 10 and 40 = " +sum); 

The function add is exported as shown in the code. The params passed are 2 integer values 10 and 40 and it returns the sum of it.


The output is displayed in the browser.

Kickstart Your Career

Get certified by completing the course

Get Started