Utilizando Rust desde Vue con WebAssembly

Rate this content
Bookmark

Rust es un nuevo lenguaje para escribir código de alto rendimiento, que puede ser compilado a WebAssembly y ejecutado dentro del navegador. En esta charla se te mostrará cómo puedes integrar Rust en una aplicación Vue de una manera sencilla y sin problemas. Con ejemplos de cómo interactuar con Rust desde JavaScript y algunas cosas a tener en cuenta.

8 min
20 Oct, 2021

Video Summary and Transcription

En esta charla, el ponente demuestra cómo utilizar Rust con WebAssembly en un proyecto Vue.js. Explica que WebAssembly es un formato binario que permite un código de alto rendimiento y un menor uso de memoria en el navegador. El ponente muestra cómo construir un ejemplo de Rust utilizando la herramienta WasmPack e integrarlo en una plantilla Vue. También demuestra cómo llamar código Rust desde un componente Vue y desplegar el paquete resultante en npm para compartirlo y consumirlo fácilmente.

Available in English

1. Introducción a Rust y WebAssembly

Short description:

Soy un líder técnico y hoy les mostraré cómo pueden usar Rust desde Vue con WebAssembly. WebAssembly es un nuevo formato binario disponible en el navegador y permite tener un código de alto rendimiento y menos memoria. He utilizado la CLI de Vue.js para generar una plantilla, pero he utilizado la versión Next. Para el lado de Rust, he instalado una herramienta llamada WasmPack para generar WebAssembly. Ahora veamos el código de Rust. Voy a iniciar un nuevo proyecto de Rust con Rasmpatch y agregar un mensaje personalizado a la alerta del navegador desde Rust.

Hola a todos. Soy un líder técnico y hoy les mostraré cómo pueden usar Rust desde Vue con WebAssembly. Así que empecemos. ¿Qué es WebAssembly? WebAssembly es un nuevo formato binario disponible en el navegador y es lo que la gente llama un objetivo de compilación en el que escribirías código en, digamos, Rust o C o C++, lo compilas a WebAssembly y luego puedes cargar ese WebAssembly usando Java strips y ejecutarlo. Esto te permite tener un código de alto rendimiento y menos memoria que si lo hubieras escrito en, digamos, Java strips. WebAssembly está disponible en todos los navegadores modernos. Entonces, ¿cómo lo usamos? Ahora voy a mostrarles un ejemplo en un momento. Para este ejemplo, he utilizado la CLI de Vue.js para generar una plantilla, pero he utilizado la versión Next. Explicaré por qué en un momento. Para el lado de Rust, he instalado una herramienta llamada WasmPack y la razón es porque obviamente no queremos generar binarios normales de Rust, queremos estar vinculados a WebAssembly y hay algunos extras adicionales que necesitaríamos configurar. WasmPack hace todo eso por ti. Así que veamos el código. Aquí tengo las plantillas que ya he generado. La razón por la que he utilizado la versión Next es porque se instala con Webpack 5. Antes de entrar en cualquier código de Rust, necesito poder consumir WebAssembly dentro del proyecto y Webpack 5 puede hacer eso. Así que voy a habilitar esa capacidad. En la configuración de Vue, voy a agregar las exportaciones de módulos que configurarán Webpack, donde bajo el experimento puedes encontrar async WebAssembly y voy a establecer eso en true. Así que ahora podré consumir WebAssembly dentro de este proyecto. Ahora veamos el código de Rust. No tengo ningún código de Rust aquí, así que voy a iniciar un nuevo proyecto de Rust con Rasmpatch, simplemente lo llamaré mi ejemplo de Rust, y eso generará un nuevo proyecto de Rust. Debido a que he utilizado Rasppatch, agrega algunos extras. Por ejemplo, ha agregado en algún lugar el Rasm bind gen para poder comunicarse con WebAssembly, así como algunos otros extras útiles ya configurados. Si entro en el código fuente proporcionado, el código fuente predeterminado, se proporcionan estas dos funciones de fábrica. Esta es una función externa, lo que significa externa a Rust. Esta alerta, esta es la alerta del navegador que está disponible. Y esa es esa función externa. Y así está llamando a la alerta del navegador en su código predeterminado desde Rust. Aquí hay una función G.R.E.A.T que se proporciona. Agreguemos un mensaje personalizado a esto. Y

2. Construyendo el Ejemplo en Rust

Short description:

Construyamos el ejemplo en Rust utilizando RasmPack build, que apunta a la cadena de herramientas de WebAssembly. La salida incluye una carpeta de paquete que contiene un paquete de nodo con el código necesario de WebAssembly, JavaScript y declaraciones de TypeScript. Agregaremos este proyecto a la plantilla de Vue modificando el archivo view package JSON, instalando las dependencias necesarias y ejecutando la plantilla en un navegador.

en lugar de llamar a esto, vamos a pasar un mensaje personalizado a la alerta del navegador desde Rust. Entonces, estoy satisfecho con eso. Construyámoslo. Voy a ir a mi ejemplo en Rust, y luego voy a hacer un RasmPack build. Y esto lo construirá apuntando a lo que se llama la cadena de herramientas de WebAssembly. Por lo tanto, genera código de WebAssembly. Y también genera algunas otras cosas que son bastante útiles. Tenemos esta carpeta de paquete que acaba de aparecer. Y esta carpeta de paquete es la salida que genera. Y esto incluye lo que es un paquete de nodo. Así que tiene un package JSON, como normalmente esperarías. Tiene, por supuesto, el código de WebAssembly. Lo necesitaremos. Tiene algo de JavaScript aquí. Así que dije antes que cargarías el WebAssembly y luego lo llamarías desde JavaScript. Bueno, me ha proporcionado ese código para que no tenga que hacerlo. E incluso ha proporcionado declaraciones de TypeScript para que pueda llamar esto desde TypeScript y obtener todos los parámetros correctos y demás. Así que agreguemos este proyecto a mi plantilla de Vue. Voy a ir al archivo view package JSON aquí abajo. Aquí está. La charla relámpago. Y estoy en las dependencias. Voy a agregar ese proyecto en Rust, mi ejemplo en Rust. Y está en el sistema de archivos. Y es mi ejemplo en Rust. Y necesito apuntar al paquete, el paquete de nodo que HasMpac construyó. Vamos a instalar eso. Vamos a hacer yarn install. Y luego hagamos un yarn serve. Y ahora tenemos la plantilla ejecutándose. Vamos a un navegador.

3. Llamando Código Rust y Desplegando en npm

Short description:

Vamos a llamar al código Rust desde la página Click Me. Al importar la función greet del ejemplo en Rust, podemos mostrar el mensaje 'Hola desde view a través de Rust' cuando se hace clic en el botón. Esta integración se logra al extraer la funcionalidad del botón en el JavaScript envolvente, que interactúa con el código de WebAssembly. El paquete resultante se puede desplegar en npm para compartirlo y consumirlo fácilmente.

Vamos aquí. Y aquí está la plantilla. Así que tengo una página en la que ya he comenzado llamada Click Me. Tiene un botón. El botón no hace nada. Vamos a llamar a ese código Rust desde aquí. Así que simplemente voy a hacer clic en mí. Aquí está ese botón. Llama al hacer clic en mí. Aquí está la función hacer clic en mí. Así como importaría algo en cualquier otro paquete o dependencia JavaScript, ahora puedo importar la función greet de mi ejemplo en Rust. Y ahora vamos a mostrar greet. Hola desde view a través de Rust. Vamos a mostrar eso. Está construido. Vamos a volver aquí. Vamos a hacer clic en mí. Y hola desde view a través de Rust. Y así ese botón, esto se ha extraído en el JavaScript envolvente en esta carpeta de paquete, que luego se extrae en el WebAssembly y de vuelta en la alerta. Así que eso es genial. Por supuesto, al ser un paquete de nodo, simplemente lo desplegamos en npm. ¿Por qué no lo hacemos ahora? Así que hay Wasm pack publish. Voy a hacer eso, Wasm pack publish y ahora está en npm. Así que ahora, en lugar de usarlo en el sistema de archivos, puedo simplemente poner el número de archivo de eso e instalar el archivo con yarn. De esa manera puedo compartirlo con otras personas, siempre y cuando puedan consumir WebAssembly. Muchas gracias. Espero que esto te haya sido útil.

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

Vue.js London Live 2021Vue.js London Live 2021
34 min
Everything Beyond State Management in Stores with Pinia
Top Content
When we think about Vuex, Pinia, or stores in general we often think about state management and the Flux patterns but not only do stores not always follow the Flux pattern, there is so much more about stores that make them worth using! Plugins, Devtools, server-side rendering, TypeScript integrations... Let's dive into everything beyond state management with Pinia with practical examples about plugins and Devtools to get the most out of your stores.
Vue.js London Live 2021Vue.js London Live 2021
20 min
One Year Into Vue 3
Top Content
Vue 3 may still sound new to many users, but it's actually been released for over a year already. How did Vue 3 evolve during this period? Why did it take so long for the ecosystem to catch up? What did we learn from this process? What's coming next? We will discuss these questions in this talk!
Vue.js London Live 2021Vue.js London Live 2021
24 min
Local State and Server Cache: Finding a Balance
Top Content
How many times did you implement the same flow in your application: check, if data is already fetched from the server, if yes - render the data, if not - fetch this data and then render it? I think I've done it more than ten times myself and I've seen the question about this flow more than fifty times. Unfortunately, our go-to state management library, Vuex, doesn't provide any solution for this.For GraphQL-based application, there was an alternative to use Apollo client that provided tools for working with the cache. But what if you use REST? Luckily, now we have a Vue alternative to a react-query library that provides a nice solution for working with server cache. In this talk, I will explain the distinction between local application state and local server cache and do some live coding to show how to work with the latter.
JSNation Live 2021JSNation Live 2021
29 min
Making JavaScript on WebAssembly Fast
Top Content
JavaScript in the browser runs many times faster than it did two decades ago. And that happened because the browser vendors spent that time working on intensive performance optimizations in their JavaScript engines.Because of this optimization work, JavaScript is now running in many places besides the browser. But there are still some environments where the JS engines can’t apply those optimizations in the right way to make things fast.We’re working to solve this, beginning a whole new wave of JavaScript optimization work. We’re improving JavaScript performance for entirely different environments, where different rules apply. And this is possible because of WebAssembly. In this talk, I'll explain how this all works and what's coming next.

Workshops on related topic

Vue.js London Live 2021Vue.js London Live 2021
169 min
Vue3: Modern Frontend App Development
Top Content
Featured WorkshopFree
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
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
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.
Vue.js London 2023Vue.js London 2023
137 min
TresJS create 3D experiences declaratively with Vue Components
Workshop
- 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
Vue.js London Live 2021Vue.js London Live 2021
176 min
Building Vue forms with VeeValidate
Workshop
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.
Vue.js London Live 2021Vue.js London Live 2021
115 min
Building full-stack GraphQL applications with Hasura and Vue 3
WorkshopFree
The frontend ecosystem moves at a breakneck pace. This workshop is intended to equip participants with an understanding of the state of the Vue 3 + GraphQL ecosystem, exploring that ecosystem – hands on, and through the lens of full-stack application development.

Table of contents
- Participants will use Hasura to build out a realtime GraphQL API backed Postgres. Together we'll walk through consuming it from a frontend and making the front-end reactive, subscribed to data changes.
- Additionally, we will look at commonly-used tools in the Vue GraphQL stack (such as Apollo Client and Urql), discuss some lesser-known alternatives, and touch on problems frequently encountered when starting out.
- Multiple patterns for managing stateful data and their tradeoffs will be outlined during the workshop, and a basic implementation for each pattern discussed will be shown.
Workshop level

NOTE: No prior experience with GraphQL is necessary, but may be helpful to aid understanding. The fundamentals will be covered.
Vue.js London Live 2021Vue.js London Live 2021
72 min
A Different Vue into Web Performance
Workshop
Solving your front-end performance problems can be hard, but identifying where you have performance problems in the first place can be even harder. In this workshop, Abhijeet Prasad, software engineer at Sentry.io, dives deep into UX research, browser performance APIs, and developer tools to help show you the reasons why your Vue applications may be slow. He'll help answer questions like, "What does it mean to have a fast website?" and "How do I know if my performance problem is really a problem?". By walking through different example apps, you'll be able to learn how to use and leverage core web vitals, navigation-timing APIs, and distributed tracing to better understand your performance problems.