Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

package generated by wasm-pack import wasm file directly, which does not work in browser #1432

Open
wighawag opened this issue Sep 6, 2024 · 1 comment

Comments

@wighawag
Copy link

wighawag commented Sep 6, 2024

🐛 Bug description

Current generated code make use of import * as wasm from "./<lib>.wasm"
This does not work in browser and require a bundler

🤔 Expected Behavior

I expect wasm-pack to generate package that can be imported without transformation in modern browser

👟 Steps to reproduce

see reproduction repo here : https://github.com/bug-reproduction/wasm-pack-in-browser

git clone https://github.com/bug-reproduction/wasm-pack-in-browser
cd wasm-pack-in-browser
wasm-pack build

Then launch a server:

python3 -m http.server 8888

navigate to http://localhost:8888/

open the console and see

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "application/wasm". Strict MIME type checking is enforced for module scripts per HTML spec.

🌍 Your environment

Include the relevant details of your environment.
wasm-pack version: .13.0
rustc version: 1.81.0 (eeb90cda1 2024-09-04)

@wighawag
Copy link
Author

So after looking into it more, the web target works in modern browser

you simply execute wasm-pack build --target web

But you then need to initialise the module.

You can do that by having a wrapper js module and make use of top level await

import init from "<your-wasm-module-package>";
export * from "<your-wasm-module-package>";
export const wasmExports = await init();

This make use of top level await so you can simply import it this way

import { greet, wasmExports } from "./wrapper.js";

greet("Your Name");

const memory = wasmExports.memory;

I feel a new target option would be useful, --target web-top-level-await that would produce mostly the same code, the only addition would be to append this single line to the js file:

export const wasmExports = await __wbg_init();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant