[WASM] "UnknownImport" when WASM is compiled from crates that declare external dependencies

Hi all,
Just started learning rust and wasm not too long ago so feel free to challenge the premise of this question if what I am doing is unreasonable to begin with.

As titled, I am running into an UnknownImport error when trying to invoke a exported function from a WASM module that is compiled from a crate that declares external dependency.

I have a WASM module that is compiled using wasm-pack build from the following crate:

use random_number::random;

pub fn add_one(operand: i32) -> i32 {
    let n: i32 = random!();
    operand + n


name = "ttt"
version = "0.1.0"
edition = "2021"

crate-type = ["cdylib", "lib"]

wasm-bindgen = "0.2"
random-number = "0.1.7"
getrandom = { version = "0.2", features = ["js"] }

The directory of crate/pkg/ looks like this after running wasm-pack build:

├── package.json
├── ttt.d.ts
├── ttt.js
├── ttt_bg.js
├── ttt_bg.wasm
└── ttt_bg.wasm.d.ts

Then I tried invoking this add_one function from another crate, the main function of which looks like the following:

use std::error;

use wasmer::{imports, wat2wasm, Instance, Module, NativeFunc, Store};

fn main() -> Result<(), Box<dyn error::Error>> {
    let wasm_bytes = std::fs::read(".../ttt/pkg/ttt_bg.wasm")?;

    let store = Store::default();
    let module = Module::new(&store, wasm_bytes)?;

    let import_object = imports! {};
    let instance = Instance::new(&module, &import_object)?;

    let add_one: NativeFunc<i32, i32> = instance.exports.get_function("add_one")?.native()?;

    println!("calling add one func...");
    let result = add_one.call(2)?;
    println!("The reuslt is: {}", result);

Upon running, I get the following error:

Error: Link(Import("./ttt_bg.js", "__wbg_randomFillSync_91e2b39becca6147", UnknownImport(Function(FunctionType { params: [I32, I32, I32], results: [] }))))

This looks like it's complaining about an indirect dependency not being accessible when the WASM export function is invoked. Am I correct in that? If so, what is the proper way of exporting the function? Or am I compiling the WASM wrong?

Thanks a lot in advance.

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.