Bundle Wasm + JS file into one using webpack
Asked Answered
P

2

17

I am currently using Emscripten to compile our C++ Code into Wasm. By doing so I output two files *.js and *.wasm. Later I use our implementation to write more Javascript code on top of that which leads us to 3 files:

 index.js
 wasmFile.js
 wasmFile.wasm

I am trying to use webpack to create a single file that will package everything at build time rather than runtime with this piece of code:

function loadScript(url = "wasmFile.js") {
    var script = document.createElement( "script" );
    script.src = url;
    document.getElementsByTagName( "head" )[0].appendChild( script );
    await new Promise<void>((res) => {
        Module.onRuntimeInitialized = () => res();
    });
}

I have looked into https://github.com/ballercat/wasm-loader However, it looks like i would need to create a WebAssembly.Instance for all my function - and the Wasm file has a lot of functions to create an instance for each.

This is how our WebPack config looks like at the moment:

module.exports = {
    entry: './src/index.ts',
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/
            },
            {
                test: /\.ts$/,
                enforce: 'pre',
                loader: 'tslint-loader',
                options: {
                    emitErrors: true
                }
            }
        ]
    },
    resolve: {
        extensions: ['.tsx', '.ts', '.js']
    },
    output: {
        filename: 'index.js',
        path: path.resolve(__dirname, 'dist')
    }
};

Is there something we are missing on this? Or another package i could use to accomplish this? Any help would be wonderful.

Thanks!

Picofarad answered 3/6, 2019 at 21:16 Comment(1)
Generally speaking, you shouldn't do that. There are ways to embed Wasm into JavaScript, but you're losing some of the main advantages of WebAssembly - lean size, streaming compilation, code caching and more. You'll have one less file at the cost of a much larger and slower bundle and it's not a tradeoff worth doing.Slow
F
2

You can build your app as a single JS file using -s SINGLE_FILE=1

Note: This answer is probably not exactly what you want but it solved similar problem for me.

Franky answered 9/11, 2021 at 11:15 Comment(0)
A
-1

Try out the --bind option. It will output a js and wasm file, the js file loads wasm files and exports the functions to be used in js.

Embind doc

Emcc doc search for bind

Antecedency answered 6/9, 2021 at 9:37 Comment(1)
That's not at all what --bind does. Emscripten outputs JS + Wasm that load each other regardless. --bind only enables Embind, which allows user to convert certain values between JavaScript and C++, but it doesn't do anything special for bundlers.Slow

© 2022 - 2024 — McMap. All rights reserved.