Benjamin Gilbert
Benjamin Gilbert

Reputation: 3

How to use WASM with nextjs via emscripten

I want to call a C++ function from my next.js component.

Using emscripten and the -sENVIRONMENT='web' -sMODULARIZE=1 flags, I compiled the C++ into main.js and main.wasm. I tried running it from a component:

import Solver from '@/wasm/main';

export default function WasmComponent() {
    const handleClick = async () => {
        const Module = await Solver();
        const test = Module.cwrap("myfunction", "string", ["string"]);
        console.log(test("test"));
    }
    
    return (
        <Button variant="contained" onClick={handleClick}>Call the WASM Function!</Button>
    )

}

The console gives me an error saying it couldn't find http://localhost/_next/static/chunks/main.wasm.
Obviously I need to load the .wasm file into the webpack, but I don't understand webpacks that well. Fiddled with next.config.mjs, nothing worked.

Alternatively, I couldn't figure out how emscripten could choose a different filepath to read the .wasm file. It would always look in http://localhost/_next/static/chunks/, and I couldn't find any options to configure it otherwise.

My theory: if I serve the file statically from a path called http://localhost/_next/static/chunks/main.wasm, then technically it will be in the right location. I manually created these directories in my next.js project's public folder, and it worked! The wasm function runs.

But it's obviously not what I'm supposed to do. What's the right way?

Upvotes: 0

Views: 603

Answers (1)

Benjamin Gilbert
Benjamin Gilbert

Reputation: 3

I eventually found the answer in this blog post. If I add the flag -sSINGLE_FILE=1 to the compilation, emscripten only generates a single .js file which has the .wasm file within it. So I don't need to figure out how to load the .wasm file.

Upvotes: 0

Related Questions