Writing WebAssembly by hand with Webpack

In this article I will focus on the usage in Webpack but if you want to learn about writing WebAssembly (using the text format) you can read this great article: Writing WebAssembly By Hand.

Webpack configuration

wast-loader

The wast-loader will take your wast file, compiles it down to a wasm binary and emits it in Webpack.

See installation notes here: wast-loader#install.

webpack.config.js

JavaScript
        
module.exports = {
  entry: "./index.js",
  module: {
    rules: [
      {
        test: /\.wast$/,
        loader: "wast-loader",
        type: "webassembly/experimental"
      }
    ]
  }
};
        
      

JavaScript

Now, thanks to the loader you can import .wast files in any JavaScript file in your project.

index.js

JavaScript
        
import("./add.wast").then(({add}) => {
  console.log("add", add(1, 2));
});
        
      

WebAssembly

add.wast

The following example is a function with two arguments (32 bits integer) and returns the sum of them. You need to export the function (here add) in order to call it from your JavaScript.

JavaScript
        
(module
  (func (export "add") (param i32 i32) (result i32)
    (get_local 0)
    (get_local 1)
    (i32.add)
  )
)
        
      

getn.wast

You can also import directly JavaScript modules from a file in your project or a package.

JavaScript
        
(module
  (import "./file.js" "n" (global i32))

  (func (export "getn") (result i32)
    (get_global 0)
  )
)
        
      

Reach out

Say hello: [email protected].

Ping me on Twitter: @svensauleau.