Search code examples
sveltewebassemblyvitewasm-pack

How to include an WASM npm module in svelte with vite?


I'm using vite to run a svelte app, and have a WASM package built with wasm-pack --target web. If I use the package directly with vanilla JS, I can write something like:

<script type="module">
    import init, { greet } from "./pkg/compiler.js";

    init().then(() => {
        greet("Hello");
    });
</script>

in an HTML file where greet is one of my wasm_bindgen functions, and that works fine.

However, my intended pipeline is to publish the pkg/ folder that wasm-pack generates to npm, and then use this package in svelte with vite, something like so:

<script lang="ts">
    import init, { greet } from "@ocr-compiler/compiler";
    
    init().then(() => {
        greet("Hello");
    });
</script>

However, this throws an error: Unknown file extension ".wasm" for /home/drbracewell/code/ocr/packages/svelte-editor/node_modules/@ocr-compiler/compiler/compiler_bg.wasm Does anyone know how I can fix this? Vite docs mention that it will automatically process .wasm files, but does this not happen when they're included from npm packages?


Solution

  • Eventually solved this using vite-plugin-wasm-pack, but a couple notes:

    • You need to bundle with the --target web flag with wasm-pack.
    • If your rust crate exists locally you should just be able to pass path in and the plugin will bundle it correctly.
    • If you intend to publish your package to or are using a WASM package from npm, you will need to add a main property to the package.json generated by wasm-pack - There's currently a pull request open to ensure that it will get added regardless of the target, but in the meantime it would be pretty simple to setup a package script that adds it to the JSON.