vite—rust执行环境

498 阅读1分钟

介于现在前端wasm呼声很高于是本菜鸡也开始了入坑之旅。 vite与vue的配置,还有rust的执行环境暂且就不说了请自行百度。 主要依赖于lencx大佬写的rsw插件

"vite-plugin-rsw": "^1.9.3"

另外需要wasm-pack全局安装(建议安装0.9.0版本) 运行命令为:cargo install wasm-pack --vers 0.9.0 vite.config.ts中配置为

image.png 文件目录结构:

image.png 在rs项目下创建一个库lib代码为:

use wasm_bindgen::prelude::*;
use serde_json::Result;
use std::collections::HashMap;
use std::string::String;

#[wasm_bindgen]
pub fn hasToJson() -> String {

    let mut scores: HashMap<String, i32> = HashMap::new();

    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);

    // Serialize it to a JSON string.
    let j: String = serde_json::to_string(&scores).expect("Failed to open hello.txt");


    // Print, write to a file, or send to an HTTP server.

    j
}

以上代码很好理解,声明一个公共函数,函数内部生命一个可变变量,类型为hasmap,在map中插入两个条目,将当前hasmap转为string(此处注意错误处理),在函数内部最后一行将转换后的数据作为返回值返回。 在前端代码中使用:

image.png 首先引入rs的这个库,因为wasm引入是异步的,需要先初始化才可以调用函数,在组件初始化的时候初始化rs库,在初始化完成以后打印返回的函数,此处需要注意,因为在rs中已经将map转为string,所有需要在进行序列化,最终控制台输出的结果为:

image.png