WebAssembly in Action

Author of the book "WebAssembly in Action"
Save 40% with the code: ggallantbl
The book's original source code can be downloaded from the Manning website and GitHub. The GitHub repository includes an updated-code branch that has been adjusted to work with the latest version of Emscripten (currently version 3.1.44).

Thursday, January 2, 2020

The import statement with an Emscripten-generated WebAssembly module in Vue.js

Over the 2019 Christmas break, I helped a developer find a way to import an Emscripten-generated WebAssembly module into Vue.js. This article details the solutions found.
In my liveBook for WebAssembly in Action, I was recently asked how to use an Emscripten-generated module in Vue.js. In the book, I showed examples using standard JavaScript but didn't dig into JavaScript frameworks so I thought this would be an interesting question to look into especially because I've never used Vue.js before.

This article will walk you through the solution that was found.

The first thing that's needed is a WebAssembly module.

The WebAssembly module

The module is kept simple with just an Add function that accepts two integer values, sums them, and returns the result. The following snippet shows the C code that's saved to a file called add.c.

#include <stdlib.h>
#include <emscripten.h>

EMSCRIPTEN_KEEPALIVE
int Add(int value1, int value2)
{
return (value1 + value2);
}

With the C code created, the next step is to compile it into a WebAssembly module.

Generating the WebAssembly module

To import the generated module into Vue.js, we want to use an import statement similar to the following:

import Module from './TestImport';

By default, the Emscripten-generated JavaScript is not configured to be imported in this fashion. To tell Emscripten to create the JavaScript so that it can be imported using the import statement, you need to include the -s EXPORT_ES6=1 and -s MODULARIZE=1 flags.

The MODULARIZE flag will wrap the generated JavaScript code's Module object in a function. Ordinarily, just including the JavaScript file in a webpage triggers the automatic download and instantiation of the module. When using this flag, however, you'll need to create an instance of the Module object to trigger the download and instantiation.

The EXPORT_ES6 flag will include the necessary export object expected by the import statement.

As we tried to import the module, however, we received an error from Vue.js about the var _scriptDir = import.meta.url; line of code in the generated JavaScript file. To get around this error, we included the -s USE_ES6_IMPORT_META=0 flag to tell Emscripten to use the older form of the import.meta.url line of code for systems that don't recognize that code.

Bringing it all together, the following command line creates a module that can be imported into Vue.js using the import statement:

emcc add.c -s EXTRA_EXPORTED_RUNTIME_METHODS=['ccall']
-s EXPORT_ES6=1 -s MODULARIZE=1 -s USE_ES6_IMPORT_META=0
-o TestImport.js

Now that you have a WebAssembly module, the next step is to import it into the Vue.js application.

The Vue.js application

The following are two approaches that I came up with for loading a module in Vue.js:
  1. Create an object on the Vue instance that is null by default. When the first component that needs the module is loaded, it creates the module instance and all components afterwards have access to the module.
  2. The other approach is to have a local object in the component where only that component has access to the module.
The first thing that you need to do is copy the TestImport.js and TestImport.wasm files to your Vue.js solution. I placed them in the src folder.

The first approach that I'll show you is where the module instance is placed on the Vue instance.

1. Module instance placed on the Vue instance

In the main.js file, create a variable on the Vue object called $myModule so that the module is only downloaded and initialized the once. The object is null until instantiated for the first time.

The following snippet shows the change in the main.js file:

import Vue from 'vue';
import App from './App.vue';

Vue.config.productionTip = true;
Vue.prototype.$myModule = null; // Will hold the module's instance

new Vue({
render: h => h(App)
}).$mount('#app');

The next area that needs to be adjusted is the component.

Adjust the component

Adjust the Home.vue component with a template that has a button that will call the callAdd function. The result of the function call will be placed below the button as shown in the following snippet:

<template>
<div>
<button @click="callAdd">Add</button>
<p>Result: {{ result }}</p>
</div>
</template>

Within the Script tag, include the import statement for the module as shown in the following snippet:

import Module from '../TestImport';

Because the module was created using the -s MODULARIZE=1 flag, the module isn't downloaded and instantiated until you create an instance of the Module object.

In the component's export object, create a beforeCreate hook that checks to see if the $myModule object has been created yet. If not, create a new instance of the Module object. The download and instantiation of the module is asynchronous so a Promise is returned. When the Promise resolves, the module instance is assigned to the $myModule object as shown in the following snippet:

beforeCreate() {
if (this.$myModule === null) {
new Module().then(myModule => {
this.$myModule = myModule;
});
}
}

The callAdd function calls into the module using Emscripten's ccall helper function as shown in the following snippet:

callAdd() {
this.result = this.$myModule.ccall('Add',
'number',
['number', 'number'],
[2, 3]);
}

Putting it all together, the following is the content of the Home.vue file:

<template>
<div>
<button @click="callAdd">Add</button>
<p>Result: {{ result }}</p>
</div>
</template>

<script>
import Module from '../TestImport';

export default {
beforeCreate() {
if (this.$myModule === null) {
new Module().then(myModule => {
this.$myModule = myModule;
});
}
},
data() {
return {
result: null
}
},
methods: {
callAdd() {
this.result = this.$myModule.ccall('Add',
'number',
['number', 'number'],
[2, 3]);
}
}
};
</script>

<style scoped>
</style>

The source code for the example above can be found here: VuejsGlobalInstance

If you don't want the module available to all components, the following is how you can use a local variable to hold the module instance instead.

2. Using a local module instance in your component

In this case, no changes are needed to your main.js file.

In the Home.vue file, create a variable called moduleInstance after the import statement as shown in the following snippet:

import Module from '../TestImport';
let moduleInstance = null;

In the beforeCreate hook, you don't need to check to see if the object exists yet. All you need to do is create an instance of the Module object and, when the Promise resolves, assign the module instance to the moduleInstance variable as shown in the following snippet:

beforeCreate() {
new Module().then(myModule => {
moduleInstance = myModule;
});
}

The callAdd function calls into the module using Emscripten's ccall helper function using the moduleInstance object as shown in the following snippet:

callAdd() {
this.result = moduleInstance.ccall('Add',
'number',
['number', 'number'],
[2, 3]);
}

Putting it all together, the following is the content of the Home.vue file:

<template>
<div>
<button @click="callAdd">Add</button>
<p>Result: {{ result }}</p>
</div>
</template>

<script>
import Module from '../TestImport';
let moduleInstance = null;

export default {
beforeCreate() {
new Module().then(myModule => {
moduleInstance = myModule;
});
},
data() {
return {
result: null
}
},
methods: {
callAdd() {
this.result = moduleInstance.ccall('Add',
'number',
['number', 'number'],
[2, 3]);
}
}
};
</script>

<style scoped>
</style>

The source code for the example above can be found here: VuejsLocalInstance

When I was trying to run this on my machine, I was getting a content-type error in the console window of my browser’s developer tools. For some reason, my Vue.js dev server isn't using the proper media type for a WebAssembly module. It should be application/wasm.

The developer I was helping didn't have an issue with this so it's probably a configuration issue with my computer (Windows with Visual Studio as the IDE). I've included this just in case anyone else runs into this issue.

To get around this issue, I needed to modify the vue.config.js file by adding the following:

const path = require('path');
const contentBase = path.resolve(__dirname, '..', '..');

module.exports = {
configureWebpack: config => {
config.devServer = {
before(app) {
// use proper mime-type for wasm files
app.get('*.wasm', function (req, res, next) {
var options = {
root: contentBase,
dotfiles: 'deny',
headers: {
'Content-Type': 'application/wasm'
}
};
res.sendFile(req.url, options, function (err) {
if (err) { next(err); }
});
});
}
}
}
}


Summary

In this article you saw that it's possible to load an Emscripten-generated WebAssembly module using the import statement if you use the -s EXPORT_ES6=1 and -s MODULARIZE=1 flags when creating the module.

If the tool you're using has an issue with the import.meta.url line of code, you can tell Emscripten to use a different set of code for that line by including the -s USE_ES6_IMPORT_META=0 flag when creating the module.

When using the -s MODULARIZE=1 flag, importing the Emscripten-generated JavaScript file won't automatically download and instantiate the module. Instead, you need to create an instance of the Module object. The download and instantiation is asynchronous so you need to either wait for the Promise to resolve, as was done in this article, or implement a callback function for the onRuntimeInitialized Emscripten function.

In Vue.js, you can add an object to the Vue instance by adding it to the prototype. When adding something to the prototype, it will be available to all components.

If you don't want your module available to all components, you can place the instance in a variable local to the component.


For this article, Emscripten 1.39.5 was used to create the WebAssembly module. Visual Studio 2019 was used to create the Vue.js application with the following devDependencies:

"@vue/cli-plugin-babel": "3.0.4",
"@vue/cli-plugin-eslint": "3.0.4",
"@vue/cli-service": "3.0.4",
"eslint": "5.6.0",
"eslint-plugin-vue": "4.7.1",
"vue-template-compiler": "2.5.17"


Additional Material on WebAssembly

Like what you read and are interested in learning more about WebAssembly?
  • Check out my book "WebAssembly in Action"

    The book introduces the WebAssembly stack and walks you through the process of writing and running browser-based applications. It also covers dynamic linking multiple modules at runtime, using web workers to prefetch a module, threading, using WebAssembly modules in Node.js, working with the WebAssembly text format, debugging, and more.

    The first chapter is free to read and, if you'd like to buy the book, it's 40% off with the following code: ggallantbl

  • Blazor WebAssembly and the Dovico Time Entry Status app

    As I was digging into WebAssembly from a C# perspective for an article that I was preparing to write, I decided to use some research time that my company gave me to dig into Blazor WebAssembly by rewriting a small Java application that I built in 2011.

    This article walks you through creating the Dovico Time Entry Status app using Blazor WebAssembly.

  • Using WebAssembly modules in C#

    While there were a lot of exciting things being worked on with the WebAssembly System Interface (WASI) at the time of my book's writing, unfortunately, it wasn't until after the book went to production that an early preview of the Wasmtime runtime was announced for .NET Core.

    I wrote this article to show you how your C# code can load and use a WebAssembly module via the Wasmtime runtime for .NET. The article also covers how to create custom model validation with ASP.NET Core MVC.

  • WebAssembly threads in Firefox

    My book shows you how to use WebAssembly threads but, at the time of its writing, they were only available in Firefox behind a flag. They're no longer behind a flag but Firefox has added a requirement: To enable the SharedArrayBuffer, you need to include two response headers.

    Although the headers are only required by Firefox desktop at the time of this article's writing, this will soon change as Chrome for Android will require the headers when version 88 is released in January 2021. Chrome desktop is expected to require the headers by March 2021.

    This article walks you through returning the response headers and using WebAssembly threads to convert a user-supplied image to greyscale.


Disclaimer: I was not paid to write this article but I am paid royalties on the sale of the book "WebAssembly in Action" which I mentioned in this article.

No comments:

Post a Comment