rustwasm / wasm-pack

📦✨ your favorite rust -> wasm workflow tool!
https://rustwasm.github.io/wasm-pack/
Apache License 2.0
6.31k stars 409 forks source link

Option to embed .wasm as a base64 string in JavaScript file #831

Open Ayrx opened 4 years ago

Ayrx commented 4 years ago

💡 Feature description

wasm-pack currently generates code similar to the following in --target nodejs where the .wasm file is read from the disk.

const path = require('path').join(__dirname, 'foo.wasm');                                                                                                                                              
const bytes = require('fs').readFileSync(path);      

I would like an option to embed the .wasm bytes as a base64 encoded string in the generated JS file that is then decoded and loaded when the JS program runs. This would be useful in scenarios where the JS engine is embedded as a scripting environment as the concept of "reading files from disk" does not work.

Pauan commented 4 years ago

Note that this must be added to wasm-bindgen first, before it can be added to wasm-pack.

webmaster128 commented 4 years ago

As far as I know, embedding Wasm as a string is the only way to be able to use the same package for browsers, bundlers and Node.js.

SabrinaJewson commented 3 years ago

Note that if you're using Webpack, you can work around this like so:

In webpack.config.js:

module.exports = {
    module: {
        rules: [
            {
                test: /\.wasm$/,
                type: "asset/inline",
            },
        ],
    },
    plugins: [
        new WasmPackPlugin({
            extraArgs: "--target web",
        }),
    ],
    // ...
};

In your Javascript file:

import initWasm, { /* other wasm imports */ } from "[path to crate]/pkg/index";
import wasmData from "[path to crate]/pkg/index_bg.wasm";
initWasm(wasmData);

Once the promise returned by initWasm resolves, the WASM module will have been loaded.

BenjaminLesne commented 6 months ago

Based on this comment, this issue prevents my nextjs project to load parquetjs.

Is there any work around?

I tried @SabrinaJewson 's solution but could not find the required crateDirectory I should give to the WasmPackPlugin constructor.