Is there some way to run JavaScript function in Rust?

I have a very large Function written by JS, I want to reuse it in my Rust lib. I have tried to use wasm-bindgen. I find it can write codes like this:

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
extern "C" {
    fn alert(s: &str);
}

#[wasm_bindgen]
pub fn greet(name: &str) {
    alert(&format!("Hello, {}!", name));
}

But, when I add a test to run greet, it throws error.

#[test]
fn test_run() {
    greet("foo")
}

Error:

running 1 test
thread 'test_run' panicked at 'cannot call wasm-bindgen imported functions on non-wasm targets', examples/import_js/crate/src/lib.rs:3:1

Is there possible to import the JS function and run it only in a Rust environment ?

To run JS function, you need some kind of JS engine, like the ones included in browsers or in Node.js. It's not something Rust can do on its own.

2 Likes

There is a section in the wasm-bindgen reference on how to test with wasm-bindgen-test. Maybe there is something in there that can make your unit test work?

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.