Utilising Rust from Vue with WebAssembly

Rate this content
Bookmark
This video explains how to use Rust with Vue.js through WebAssembly. It covers setting up a Vue.js project using the Vue CLI and integrating Rust code compiled to WebAssembly using WasmPack. The video demonstrates creating a Rust project, generating WebAssembly code, and integrating it into a Vue.js project. Key topics include WebAssembly's benefits, such as high performance and efficient memory usage, and the tools needed for integration, like Webpack 5 and WasmPack. The process of publishing Rust-generated WebAssembly packages to npm is also discussed.

From Author:

Rust is a new language for writing high-performance code, that can be compiled to WebAssembly, and run within the browser. In this talk you will be taken through how you can integrate Rust, within a Vue application, in a way that's painless and easy. With examples on how to interact with Rust from JavaScript, and some of the gotchas to be aware of.

This talk has been presented at Vue.js London Live 2021, check out the latest edition of this Tech Conference.

FAQ

WebAssembly is a new binary format available in the browser, often referred to as a compilation target. You can write code in languages like Rust, C, or C++, compile it to WebAssembly, and then load and execute it using JavaScript. This allows for high-performance code with less memory usage compared to JavaScript.

WebAssembly can be used in modern web development by compiling code written in languages like Rust into WebAssembly. This compiled code can then be loaded and executed in the browser using JavaScript, enabling high-performance and efficient memory usage.

To use Rust with WebAssembly in a Vue.js project, you'll need the Vue.js CLI to generate a project template and Webpack 5 for module bundling. Additionally, you'll need WasmPack, a tool that helps generate WebAssembly-compatible Rust binaries and includes useful extras such as wasm-bindgen.

To configure Webpack to consume WebAssembly in a Vue.js project, you need to enable the 'async WebAssembly' feature in the Webpack configuration. This can be done by adding 'module.exports' in the 'vue.config.js' file and setting 'experiments.asyncWebAssembly' to true.

WasmPack is a tool that helps compile Rust code to WebAssembly. It is necessary because it not only generates WebAssembly-compatible binaries but also includes additional tools and configurations, such as wasm-bindgen, to facilitate communication between Rust and WebAssembly.

To create a new Rust project for WebAssembly, you can use WasmPack to generate a new project template. This template includes necessary configurations and default functions, such as wasm-bindgen for WebAssembly communication and browser alerts.

To integrate Rust-generated WebAssembly code into a Vue.js project, compile the Rust code using WasmPack to generate a package folder containing the WebAssembly code, JavaScript, and TypeScript declarations. Then, add this package to the Vue.js project's 'package.json' file and install it using a package manager like yarn.

To deploy a Rust-generated WebAssembly package to npm, use the 'wasm-pack publish' command. This will publish the package to npm, making it available for others to install and use directly from the npm registry.

To call a Rust function from Vue.js, first import the Rust function into your Vue.js component just like any other JavaScript module. Then, you can call the function within your component's methods, such as an event handler for a button click.

WebAssembly offers higher performance and more efficient memory usage compared to JavaScript. It allows developers to write code in languages like Rust, C, or C++ and compile it to a binary format that can be executed in the browser, making it suitable for performance-critical applications.

Joe Lenton
Joe Lenton
8 min
20 Oct, 2021

Comments

Sign in or register to post your comment.

Video Transcription

1. Introduction to Rust and WebAssembly

Short description:

I'm a tech lead and today I'm going to be showing you how you can use Rust from Vue with WebAssembly. WebAssembly is a new binary format available in the browser and it allows you to have high-performance code and less memory. I've used the Vue.js CLI to generate a template but I've used the Next version. For Rust side, I've installed a tool called WasmPack to generate WebAssembly. Now let's look at Rust code. I'm going to start a new Rust project with Rasmpatch and add a custom message to the browser alert from Rust.

Hello, everyone. I'm a tech lead and today I'm going to be showing you how you can use Rust from Vue with WebAssembly. So let's get started.

What is WebAssembly? WebAssembly is a new binary format available in the browser and it's what people call a compilation target in that you would write code in say Rust or C or C++, you compile that to WebAssembly and then you can load that WebAssembly using Java strips and execute that WebAssembly. This allows you to have high-performance code and less memory than if you'd have written in say Java strips. WebAssembly is available in all modern browsers.

So how do we use it? I'm now going to go into an example in a moment. For this example I've used the Vue.js CLI to generate a template but I've used the Next version. I'll explain why in a moment. For Rust side I've installed a tool called WasmPack and the reason why is because obviously we don't want to generate normal Rust binaries, we want to be tied to WebAssembly and there's a few other extras that we would need to set up. WasmPack does all of that for you.

So let's hop into the code. Here I have the templates that I've already generated. The reason why I've used the Next version is because it installs with Webpack 5. Before we get into any Rust code, I need to be able to consume WebAssembly within the project and Webpack 5 can do that. So I'm going to be turning on the ability to do that. In the view config I'm going to be adding the module exports which will configure Webpack where under the experiment you can find async WebAssembly and I'm going to be setting that to true. So now I'll be able to consume WebAssembly within this project. Now let's look at Rust code. I don't have any Rust code here so I'm going to start a new Rust project with Rasmpatch, I'm just going to call it my Rust example, and that will generate a brand new Rust project. Because I've used Rasppatch, it adds in a few extras. So for example, it's added in somewhere the Rasm bind gen for being able to talk to WebAssembly, as well as a few other useful extras already set up. If I go into the source code that's provided, the default source code, it's provided these two functions out of the box. This is an external function and so it means external to Rust. This alert, this is the browser alert that's available. And so that's that external function. And so it's calling the browser alert already in its default code from Rust. Here is a G.R.E.A.T function that is provided. Let's add on a custom message to this. And instead of calling this, let's pass a custom message to the browser alert from Rust.

2. Building the Rust Example

Short description:

Let's build the Rust example using RasmPack build, which targets the WebAssembly toolchain. The output includes a package folder containing a node package with the necessary WebAssembly code, JavaScript, and TypeScript declarations. We'll add this project to the view template by modifying the view package JSON, installing the necessary dependencies, and running the template in a browser.

So I'm happy with that. Let's build it. So I'm going to go into my Rust example, and then I'm going to do a RasmPack build. And this will build it targeting what's called WebAssembly toolchain. So it outputs WebAssembly code. And it also outputs a few other things which are quite useful.

We have this package folder that's just showing up. And this package folder is the output that that generates. And this includes what is a node package. So it has a package JSON, just as you would normally expect. It has, of course, the WebAssembly code. We'll need that. It has some JavaScript here. So I said before you would load the WebAssembly and then call it from JavaScript. Well, it's provided that code for me so that I don't need to do that. And it's even provided TypeScript declarations so that I can call this from TypeScript and get all of the correct parameters and such.

So let's add this project to my view template. I'm going to come down to the view package JSON down here. Here it is. The lightning talk. And I'm in the dependencies. I'm going to add on that Rust project, my Rust example. And it's on the file system. And it's my Rust example. And I need to point to the package, the node package that HasMpac built. Let's install that. Let's do yarn install. And then let's do a yarn serve. And now we have the template running. Let's go to a browser.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Everything Beyond State Management in Stores with Pinia
Vue.js London Live 2021Vue.js London Live 2021
34 min
Everything Beyond State Management in Stores with Pinia
Top Content
State management is not limited to complex applications and transitioning to a store offers significant benefits. Pinia is a centralized state management solution compatible with Vue 2 and Vue 3, providing advanced devtools support and extensibility with plugins. The core API of Pinia is similar to Vuex, but with a less verbose version of stores and powerful plugins. Pinia allows for easy state inspection, error handling, and testing. It is recommended to create one file per store for better organization and Pinia offers a more efficient performance compared to V-rex.
Welcome to Nuxt 3
Vue.js London Live 2021Vue.js London Live 2021
29 min
Welcome to Nuxt 3
Top Content
Nux3 has made significant improvements in performance, output optimization, and serverless support. Nuxt Bridge brings the Nitro engine for enhanced performance and easier transition between Nuxt 2 and Nuxt Read. Nuxt 3 supports Webpack 5, Bytes, and Vue 3. NextLab has developed brand new websites using Docus technology. Nuxt.js is recommended for building apps faster and simpler, and Nuxt 2 should be used before migrating to Nuxt 3 for stability. DOCUS is a new project that combines Nuxt with additional features like content modules and an admin panel.
One Year Into Vue 3
Vue.js London Live 2021Vue.js London Live 2021
20 min
One Year Into Vue 3
Top Content
Vue 3 has seen significant adoption and improvements in performance, bundle size, architecture, and TypeScript integration. The ecosystem around Vue 3 is catching up, with new tools and frameworks being developed. The Vue.js.org documentation is undergoing a complete overhaul. PNIA is emerging as the go-to state management solution for Vue 3. The options API and composition API are both viable options in Vue 3, with the choice depending on factors such as complexity and familiarity with TypeScript. Vue 3 continues to support CDN installation and is recommended for new projects.
Vue: Feature Updates
Vue.js London 2023Vue.js London 2023
44 min
Vue: Feature Updates
Top Content
The Talk discusses the recent feature updates in Vue 3.3, focusing on script setup and TypeScript support. It covers improvements in defining props using imported types and complex types support. The introduction of generic components and reworked signatures for defined components provides more flexibility and better type support. Other features include automatic inference of runtime props, improved define emits and defined slots, and experimental features like reactive props destructure and define model. The Talk also mentions future plans for Vue, including stabilizing suspense and enhancing computer invalidations.
Local State and Server Cache: Finding a Balance
Vue.js London Live 2021Vue.js London Live 2021
24 min
Local State and Server Cache: Finding a Balance
Top Content
This Talk discusses handling local state in software development, particularly when dealing with asynchronous behavior and API requests. It explores the challenges of managing global state and the need for actions when handling server data. The Talk also highlights the issue of fetching data not in Vuex and the challenges of keeping data up-to-date in Vuex. It mentions alternative tools like Apollo Client and React Query for handling local state. The Talk concludes with a discussion on GitLab going public and the celebration that followed.
Making JavaScript on WebAssembly Fast
JSNation Live 2021JSNation Live 2021
29 min
Making JavaScript on WebAssembly Fast
Top Content
WebAssembly enables optimizing JavaScript performance for different environments by deploying the JavaScript engine as a portable WebAssembly module. By making JavaScript on WebAssembly fast, instances can be created for each request, reducing latency and security risks. Initialization and runtime phases can be improved with tools like Wiser and snapshotting, resulting in faster startup times. Optimizing JavaScript performance in WebAssembly can be achieved through techniques like ahead-of-time compilation and inline caching. WebAssembly usage is growing outside the web, offering benefits like isolation and portability. Build sizes and snapshotting in WebAssembly depend on the application, and more information can be found on the Mozilla Hacks website and Bike Reliance site.

Workshops on related topic

Vue3: Modern Frontend App Development
Vue.js London Live 2021Vue.js London Live 2021
169 min
Vue3: Modern Frontend App Development
Top Content
Featured WorkshopFree
Mikhail Kuznetcov
Mikhail Kuznetcov
The Vue3 has been released in mid-2020. Besides many improvements and optimizations, the main feature of Vue3 brings is the Composition API – a new way to write and reuse reactive code. Let's learn more about how to use Composition API efficiently.

Besides core Vue3 features we'll explain examples of how to use popular libraries with Vue3.

Table of contents:
- Introduction to Vue3
- Composition API
- Core libraries
- Vue3 ecosystem

Prerequisites:
IDE of choice (Inellij or VSC) installed
Nodejs + NPM
Using Nitro – Building an App with the Latest Nuxt Rendering Engine
Vue.js London Live 2021Vue.js London Live 2021
117 min
Using Nitro – Building an App with the Latest Nuxt Rendering Engine
Top Content
Workshop
Daniel Roe
Daniel Roe
We'll build a Nuxt project together from scratch using Nitro, the new Nuxt rendering engine, and Nuxt Bridge. We'll explore some of the ways that you can use and deploy Nitro, whilst building a application together with some of the real-world constraints you'd face when deploying an app for your enterprise. Along the way, fire your questions at me and I'll do my best to answer them.
Monitoring 101 for React Developers
React Summit US 2023React Summit US 2023
107 min
Monitoring 101 for React Developers
Top Content
WorkshopFree
Lazar Nikolov
Sarah Guthals
2 authors
If finding errors in your frontend project is like searching for a needle in a code haystack, then Sentry error monitoring can be your metal detector. Learn the basics of error monitoring with Sentry. Whether you are running a React, Angular, Vue, or just “vanilla” JavaScript, see how Sentry can help you find the who, what, when and where behind errors in your frontend project. 
Workshop level: Intermediate
TresJS create 3D experiences declaratively with Vue Components
Vue.js London 2023Vue.js London 2023
137 min
TresJS create 3D experiences declaratively with Vue Components
Workshop
Alvaro Saburido
Alvaro Saburido
- Intro 3D - Intro WebGL- ThreeJS- Why TresJS- Installation or Stackblitz setup - Core Basics- Setting up the Canvas- Scene- Camera- Adding an object- Geometries- Arguments- Props- Slots- The Loop- UseRenderLoop composable- Before and After rendering callbacks- Basic Animations- Materials- Basic Material- Normal Material- Toon Material- Lambert Material- Standard and Physical Material- Metalness, roughness - Lights- AmbientLight- DirectionalLight- PointLights- Shadows- Textures- Loading textures with useTextures- Tips and tricks- Misc- Orbit Controls- Loading models with Cientos- Debugging your scene- Performance
Building Vue forms with VeeValidate
Vue.js London Live 2021Vue.js London Live 2021
176 min
Building Vue forms with VeeValidate
Workshop
Abdelrahman Awad
Abdelrahman Awad
In this workshop, you will learn how to use vee-validate to handle form validation, manage form values and handle submissions effectively. We will start from the basics with a simple login form all the way to using the composition API and building repeatable and multistep forms.

Table of contents:
- Introduction to vee-validate
- Building a basic form with vee-validate components
- Handling validation and form submissions
- Building validatable input components with the composition API
- Field Arrays and repeatable inputs
- Building a multistep form
Prerequisites:
VSCode setup and an empty Vite + Vue project.
Building Pinia From Scratch
Vue.js Live 2024Vue.js Live 2024
70 min
Building Pinia From Scratch
Workshop
Eduardo San Martin Morote
Eduardo San Martin Morote
Let's dive into how Pinia works under the hood by building our own `defineStore()`. During this workshop we will cover some advanced Vue concepts like dependency Injection and effect scopes. It will give you a better understanding of Vue.js Composition API and Pinia. Requirements: experience building applications with Vue and its Composition API.