Here, we have a function, appendStringToBody, that accepts a text and adds it to the body. In our utils library, we import the function and invoke it with a string. If we run our example, we will see only a number being appended to the document.
To get started, we add wasm-bindgen as a dependency to our Cargo configuration. Then we use the extern create declaration to link the wasm-bindgen create to this new library. After that, we use the use declaration to make all functions from wasm-bindgen preload.
We can see our run as well as our appendStringToBody function are in there. This is great, because now, we can import this module, use it, and work with other than just primitive numeric types. The generated code will take care of the proper serialization.
In this example, we're going to use webpack. We start out by creating a package.json, and then installing webpack, the webpack CLI, and the webpack dev server. Then we create a webpack.config.js file, and fill it with the minimal configuration.
Now, we create our index.js file, where we import our utils module dynamically, and wait for the promise to resolve to then invoke run. Currently, this dynamic import is necessary to load a WASM module. It is a known limitation in webpack, and hopefully will be resolved soon.
Next, we need to update our index.html file to only load the index.js script. This leads to an interesting factor. We can't provide our appendStringToBody manually anymore, since loading the WebAssembly file is done inside our generated utils.js file.
What can we do instead is create a new module and export our function. When using wasm-bindgen, we then can declare that the module should be imported. We rebuild our project using wasm-pack build again, and then we review the new utils.js file.