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: