有没有一种方法可以在 WebAssembly 中与 Rust 代码一起使用 npm 包?目前,使用已经存在于此模板中的 webpack、@wasm-tool/wasm-pack-plugin 和 wasm_bindgen crate:https://github.com/rustwasm/rust-webpack-template/tree/master/template
TIA。
有没有一种方法可以在 WebAssembly 中与 Rust 代码一起使用 npm 包?目前,使用已经存在于此模板中的 webpack、@wasm-tool/wasm-pack-plugin 和 wasm_bindgen crate:https://github.com/rustwasm/rust-webpack-template/tree/master/template
TIA。
是的,有一种方法可以在您的Rust / wasm代码中使用npm包。
假设您想要使用通过npm i date-fns
安装的date-fns包,并且您想在Rust项目中使用它。
这是我所做的。-捆绑您的JavaScript并将其与wasm-bindgen一起使用 文件夹结构
正如您在图片中看到的那样,我将我的node_modules / package.json,cargo.toml放在同一个文件夹中,以方便使用。
npm i esbuild
用于esbuild。这是为了捆绑您的JavaScript。
这是我的esbuild.js
esbuild.build({
entryPoints: ['package.js'],
bundle: true,
outfile: 'src/package.js',
format: 'esm',
minify: true,
}).catch(() => process.exit(1));
package.json
中添加构建命令
"esbuild":"node esbuild.js"
import { format } from 'date-fns';
export function Dateformat(date, formatString) {
return format(date, formatString);
}
运行 esbuild 命令 npm run esbuild
,运行命令后您将在 src 文件夹中看到 package.js。这是您可以在 Rust 项目中使用的 JavaScript 代码。
使用 wasm-bindgen 导入 JavaScript
use js_sys::Date;
use wasm_bindgen::prelude::*;
#[wasm_bindgen(module = "/src/package.js")]
extern "C" {
fn Dateformat(date: &Date, formatString: &str) -> String;
}
#[wasm_bindgen]
pub fn my_format(date: &Date, format_string: &str) -> String {
Dateformat(date, format_string)
}
// this is the project set up with yew.
use js_sys::Date;
use yew::prelude::*;
use crate::pages::date_fns::my_format;
#[function_component(NpmCode)]
pub fn npm_code() -> Html {
let date = use_state(|| Option::<String>::None);
let onclick = {
let date = date.clone();
Callback::from(move |_| {
let now = Date::new_0();
let formatted_date = my_format(&now, "'Today is a' eeee");
date.set(Some(formatted_date));
})
};
html! {
<div class="flex flex-col items-center">
<p class="text-lg font-bold mb-2">{"This time is generated with date-fns npm package"}</p>
<p class="text-gray-500 mb-4">{date.clone().as_ref().map(|d| d.as_str()).unwrap_or("null")}</p>
<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded" {onclick}>
{"Generate Date"}
</button>
</div>
}
}
我还制作了一个概念验证,您可以使用 wasm-bindgen 直接在浏览器中下载 JavaScript。请查看下面的链接。 https://github.com/jinseok9338/WASM-POC 我需要更新 ReadMe,以便您更好地理解。这将在接下来的几周内完成。