{{announcement.body}}
{{announcement.title}}

The Import Statement With an Emscripten-Generated WebAssembly Module in Vue.js

DZone 's Guide to

The Import Statement With an Emscripten-Generated WebAssembly Module in Vue.js

In this article, we discuss how to add an import an Emscriptgen-generated WebAssembly module (written in C) in Vue.js.

· Web Dev Zone ·
Free Resource

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 I 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.

C


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:

JavaScript


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.

You may also like: WebAssembly vs. JavaScript.

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 creates a module that can be imported into Vue.js using an import statement:

Shell


Now that you have a WebAssembly module, the next step is to import it into your 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 created afterward 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 once. The object is null until instantiated. 

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

JavaScript


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:

HTML


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

JavaScript


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:  

JavaScript


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

JavaScript


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

HTML
 




x


1
<template>
2
  <div>
3
    <button @click="callAdd">Add</button>
4
    <p>Result: {{ result }}</p>
5
  </div>
6
</template>
7
 
          
8
<script>
9
  import Module from '../TestImport';
10
  export default {
11
    beforeCreate() {
12
      if (this.$myModule === null) {
13
        new Module().then(myModule => {
14
          this.$myModule = myModule;
15
        });
16
      }
17
    },
18
    data() {
19
      return {
20
        result: null
21
      }
22
    },
23
    methods: {
24
      callAdd() {
25
        this.result = this.$myModule.ccall('Add',
26
            'number',
27
            ['number', 'number'],
28
            [2, 3]);
29
      }
30
    }
31
  };
32
</script>
33
 
          
34
<style scoped>
35
</style>


 

The source code for the example above can be found here: https://github.com/cggallant/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:

JavaScript


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:

JavaScript


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

JavaScript


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

HTML
 




x


1
<template>
2
  <div>
3
    <button @click="callAdd">Add</button>
4
    <p>Result: {{ result }}</p>
5
  </div>
6
</template>
7
 
          
8
<script>
9
  import Module from '../TestImport';
10
  let moduleInstance = null;
11
  export default {
12
    beforeCreate() {
13
      new Module().then(myModule => {
14
        moduleInstance = myModule;
15
      });
16
    },
17
    data() {
18
      return {
19
        result: null
20
      }
21
    },
22
    methods: {
23
      callAdd() {
24
        this.result = moduleInstance.ccall('Add',
25
            'number',
26
            ['number', 'number'],
27
            [2, 3]);
28
      }
29
    }
30
  };
31
</script>
32
 
          
33
<style scoped>
34
</style>



The source code for the example above can be found here: https://github.com/cggallant/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:

JavaScript


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, 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:    

JavaScript


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.


Further Reading

Topics:
webassembly ,emscripten ,vue.js ,import statements ,tutorial ,web dev

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}