用到的库
- wasm-bindgen
- serde_json
- anyhow
用到的工具
cargo install wasm-pack
Cargo.toml
[package]
name = "wasm-bindgen-record"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
anyhow = "1.0"
wasm-bindgen = "0.2"
serde_json = "1.0"
src/lib.rs
use anyhow::Result;
use serde_json::{from_str, to_string_pretty, Value};
use wasm_bindgen::prelude::{JsValue, wasm_bindgen};
#[wasm_bindgen]
extern {
fn alert(s: &str);
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
}
#[wasm_bindgen]
pub fn format(s: &str) -> JsValue {
JsValue::from(pretty(s).unwrap())
}
fn pretty(s: &str) -> Result<String> {
Ok(to_string_pretty(&from_str::<Value>(s)?)?)
}
#[wasm_bindgen(start)]
pub fn start() {
log("Wasm");
}
#[test]
fn test() -> Result<()> {
assert_eq!(pretty(r#"{"key":"value"}"#)?, r#"{
"key": "value"
}"#);
Ok(())
}
index.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>index</title>
<style>
html, body {
height: 100%;
}
textarea {
width: 100%;
height: 50%;
}
button {
width: 20%;
height: 10%;
font-size: 2rem;
display: block;
margin: auto;
}
</style>
</head>
<body>
<textarea>{"key":"value"}</textarea>
<button>format</button>
<script>
const button = document.querySelector('button')
const textarea = document.querySelector('textarea')
import('./pkg/wasm_bindgen_record.js').then(async wasm => {
await wasm.default()
button.onclick = () => textarea.value = wasm.format(textarea.value)
})
</script>
</body>
</html>
发布至浏览器
wasm-pack build --release --target web
|