Como criar seu primeiro código WebAssembly com Rust

Apr 09 2023
Neste artigo, descreveremos o que fazer para criar seu primeiro código WebAssemly. Vamos supor que você já tenha ouvido falar algo sobre WebAssembly, mas ainda não escreveu seu primeiro código com esta tecnologia.

Neste artigo, descreveremos o que fazer para criar seu primeiro código WebAssemly.

Vamos supor que você já tenha ouvido falar algo sobre WebAssembly, mas ainda não escreveu seu primeiro código com esta tecnologia.

Por enquanto, vamos fazer um pacote inicial simples. Escolhi a combinação com a linguagem de programação Rust porque é atraente.

Sem mais delongas vamos fazer.

Instalar ferrugem e carga

Rust: linguagem de programação multiparadigma, de alto nível e de uso geral (https://www.rust-lang.org/)
Cargo: a ferramenta de compilação Rust e o gerenciador de pacotes (https://crates.io/)

Arquivo Init Cargo.toml

cargo init --name rust_wasm_starter --lib
# Cargo.toml

[package]
name = "rust_wasm_starter"
version = "0.1.0"
edition = "2021"

[dependencies]

cargo add wasm-bindgen

# Cargo.toml

[package]
name = "rust_wasm_starter"
version = "0.1.0"
edition = "2021"

[dependencies]
wasm-bindgen = "0.2.84"

cargo install wasm-pack

[lib]
crate-type = ["cdylib", "rlib"]

use wasm_bindgen::prelude::wasm_bindgen;

#[wasm_bindgen]
pub fn add(a: usize, b: usize) -> usize {
    return a + b
}

wasm-pack build --release --target web

npm init
// package.json

{
  "name": "rust-wasm-starter",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {},
  "author": "",
  "license": "ISC"
}

npm i http-server --save

"scripts": {
  "start": "http-server -a localhost -p 5200",
  "build": "wasm-pack build --release --target web"
}

import init from "./pkg/rust_wasm_starter.js";
import {add} from "../pkg/rust_wasm_starter.js";

function run() {
    console.log(add(5, 5));
}

init().then(run)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Rust Wasm Starter</title>
    <script type="module" src="./index.js"></script>
</head>
<body>
    See the result in the console.
</body>
</html>

npm run start
Starting up http-server, serving ./

http-server version: 14.1.1
CORS: disabled
Cache: 3600 seconds
Connection Timeout: 120 seconds
Directory Listings: visible
AutoIndex: visible
Serve GZIP Files: false
Serve Brotli Files: false
Default File Extension: none

Available on:
  http://localhost:5200
Hit CTRL-C to stop the server

      
                

Se você está tendo problemas para colocar o projeto em funcionamento, tente verificar meu repositório GitHub