How to import javascript function from Wasm?

I'm trying to import a javascript function from Wasm.

For the worker.ts, I defined a function consoleLog:

import mod from '../build/out.wasm';

const importObject = {
  imports: {
    consoleLog: (arg: number) => {
      console.log(`Hello from JavaScript: ${arg}`);
    },
  },
};

const instance = await WebAssembly.instantiate(mod, importObject);

export default {
  async fetch() {
    const retval = instance.exports.add100(2, 5);
    return new Response(`Success: ${retval}`);
  },
};


And I'm using AssemblyScript for the Wasm side:

declare function consoleLog(arg0: i32): void;

export function add100(a: i32, b: i32): i32 {  
  // consoleLog(100);
  return a + b + 100;
}


Since I commented the //consoleLog(100); out, it works well after compile:

asc assembly/index.ts --outFile build/out.wasm --optimize


However, when I un-commented it as:

declare function consoleLog(arg0: i32): void;

export function add100(a: i32, b: i32): i32 {  
  consoleLog(100);
  return a + b + 100;
}


I got an error after asc:

service core:user:wasm102: Uncaught Error: No such module "bea1e1adde3b4c3c5cbc0842c823a3c93a930163-out.wasm".
  imported from "worker.js"
✘ [ERROR] MiniflareCoreError [ERR_RUNTIME_FAILURE]: The Workers runtime failed to start. There is likely additional logging output above.


Just wondering what's the appropriate way to import javascript function from Wasm?
Was this page helpful?