How do I Import Wasms into my React Project

So I been searching and have had no clear “How To” I have built a wasm object that holds parseJson function as so

pub export fn parseJson(json_str: [*]const u8, len: usize) [*]const u8 {
    const input = json_str[0..len];
    const parsed = json.parseFromSlice(QuestList, allocator, input, .{}) catch {
        // Return an empty string if parsing fails
        return "";
    };
    const result = json.stringifyAlloc(allocator, parsed.value, .{}) catch {
        return "";
    };
    return result.ptr;
}

I have ran

zig build-lib zigStuff.zig -target wasm32-wasi -O ReleaseSmall

and now I am stuck on being able to see my functions. I’ve tried

WebAssembly.instantiateStreaming(fetch("./../wasms/FetchQuestList.wasm"))
  .then(({ instance }) => {
   const {parseJson} =  instance.exports
   const questListObject: questlist = parseJson(questlistPath)
   return questListObject
  });

but its not recognizing the parseJson as a function.

If you could point me in the right direction I would appreciate it.

Try this command to build your Wasm binary instead:

zig build-exe zigStuff.zig -target wasm32-wasi -O ReleaseSmall -fno-entry -rdynamic

The Wasm binary you load using JavaScript should be an executable (hence build-exe rather than build-lib), but if you want to use it only for exported functions rather than as a traditional executable with a main function, you need -fno-entry to disable that. Additionally, -rdynamic is used to ensure that all the functions you export are actually exposed in the final output (the 0.11.0 release notes have a section that goes into more detail on why export alone isn’t enough here).

3 Likes

Thank you so much for the response

1 Like