Hello, World!
View full source code or view the compiled example online
This is the "Hello, world!" example of #[wasm_bindgen]
showing how to set up
a project, export a function to JS, call it from JS, and then call the alert
function in Rust.
Cargo.toml
The Cargo.toml
lists the wasm-bindgen
crate as a dependency.
Also of note is the crate-type = ["cdylib"]
which is largely used for wasm
final artifacts today.
[package]
authors = ["The wasm-bindgen Developers"]
edition = "2021"
name = "hello_world"
publish = false
version = "0.0.0"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = { path = "../../" }
[lints]
workspace = true
src/lib.rs
Here we define our Rust entry point along with calling the alert
function.
# #![allow(unused_variables)] #fn main() { use wasm_bindgen::prelude::*; #[wasm_bindgen] extern "C" { fn alert(s: &str); } #[wasm_bindgen] pub fn greet(name: &str) { alert(&format!("Hello, {}!", name)); } #}
index.js
Our JS entry point is quite small!
import { greet } from './pkg';
greet('World');
Webpack-specific files
Note: Webpack is required for this example, and if you're interested in options that don't use a JS bundler see other examples.
And finally here's the Webpack configuration and package.json
for this
project:
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const WasmPackPlugin = require("@wasm-tool/wasm-pack-plugin");
module.exports = {
entry: './index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js',
},
plugins: [
new HtmlWebpackPlugin(),
new WasmPackPlugin({
crateDirectory: path.resolve(__dirname, ".")
}),
],
mode: 'development',
experiments: {
asyncWebAssembly: true
}
};
package.json
{
"scripts": {
"build": "webpack",
"serve": "webpack serve"
},
"devDependencies": {
"@wasm-tool/wasm-pack-plugin": "1.5.0",
"html-webpack-plugin": "^5.6.0",
"webpack": "github:daxpedda/webpack#externref",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^5.0.4"
}
}