Wasm_bindgen and js_sys showing error in browser

I am compiling rust to wasm with wasm-pack. I am using wasm_bindgen and js_sys. The code I am writing so far is very simple. Everything works normally until I start using js sys, I get the error

Module not found: Can't resolve 'wbg'

from next.js.

This works:

#[wasm_bindgen] //Get distance based on starting x,y and ending x,y
pub fn get_distance_4p(sx: f32, sy: f32, ex:f32, ey: f32) -> f32 {
    let delta_x: f32 = sx - ex;
    let delta_y: f32 = sy - ey;
    let sqrt_x: f32 = delta_x.powf(2.0);
    let sqrt_y: f32 = delta_y.powf(2.0);
    let _c = Float32Array::new_with_length(10);
    (sqrt_x + sqrt_y).sqrt()

but once I add a second fn using js_sys I get the above error. For example:

pub fn return_jsarr(arr: &Float32Array) -> Float32Array {
    let r: Vec<f32>= arr.to_vec();
    let out: Vec<f32> = r.into_iter()
        .map(|x| x * 2.0)

I am import the wasm into my next project as follows

import {
} from "@/public/pkg/recad_wasm_bg.wasm";

useEffect(() => {
}, [])

Anything will help, I am just getting into rust and wasm so my problem might be simple.
For reference here is my cargo.toml

name = "recad-wasm"
version = "0.1.0"
edition = "2021"

crate-type = ["cdylib"]

js-sys = "0.3.64"
wasm-bindgen = "0.2.87"

When I compile I run wasm-pack build --target web

Thanks again

You can't directly import the .wasm module for wasm-bindgen based projects. Wasm-bindgen creates a wrapper .js file that you need to import instead. This .js file provides the wasm module with access to all javascript interfaces it needs.

1 Like

The thing is that when I only use wasm bind gen I can just import the wasm module like that. But when I add the js_sys it doesn’t allow me to use it. You’re saying just import the js file that the compiler gives me?

Yes - if you look at the generated JavaScript file, you'll see that it provides various bits of JavaScript that bind the WebAssembly module with JavaScript. Without those little snippets, you have a raw WASM module without any of the bindgen bits that link WASM and JavaScript together.

I figured out what I needed to do. What you said helped me find it so thank you. I had to install the module into my project (I think) and also call the default export init function from the js module first before doing anything else.