I'm looking at migrating a TupeScript library that is slow ( jackson-js ) to WASM using rust.
This library has several dependencies ( such as reflect-metadata for instance ).
These dependencies are already developed and available in npmjs. I cannot imagine developing such a dependency in rust.
Is it possible to call npm dependency from Rust ( expected to be compiled into WASM)?
Maybe by exposing some functions to the window
of the browser ( but it can lead to conflict or maybe serious security problem? )
Any other way?
It'll be a tedious work of declaring all data types and functions of the dependencies (unless someone has already done that for you), but it's definitely possible. For example, for Reflect.defineMetadata()
defined by reflect-metadata
:
#[allow(non_snake_case)]
mod Reflect {
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = Reflect)]
pub fn defineMetadata(metadataKey: &str, metadataValue: JsValue, target: &JsValue);
}
}
You can define all methods, including Node.js own require()
, in the same way. Look how libraries like js-sys
and web-sys
declare functionality and learn.
However, it seems like you misunderstand something. reflect-metadata
is a reflection library for JavaScript, not WASM. You cannot use it to add metadata on Rust objects, only JS objects. So its usefulness will be limited at best.
Also, if your code calls a lot of JavaScript libraries, it won't be any faster by porting it to WASM, probably slower. You can only expect a speedup if your code is computation heavy or allocates a lot and you can avoid it with Rust.