How to use embedded Webassembly in Vite?

8.9k views Asked by At

I would like to use this great package: https://github.com/hpcc-systems/hpcc-js-wasm It bundles a Webassembly (graphizlib.wasm) with the Javascript functions to use. I added it as a dependency in package.json.

  "dependencies": {
    "@hpcc-js/wasm": "^1.13.0"
  },

When I now run the Vite dev server then the Javascript code is found easily enough. But the wasm isn't available. In particular, I get this error message:

Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:3000/graphvizlib.wasm

I am not sure how to make the embedded web assembly available for my site. It is in the dependency package. See #1, within the node_modules (#2), in the @hpcc-js/wasm/dist folder (#3) enter image description here

I tried it as well with the build configuration of Vite - without access.

2

There are 2 answers

1
Schmoo On BEST ANSWER

Basically you need to treat the wasm file like any "static asset" (like a png or jpeg). Based on where the browser is looking for the file by default, the quickest solution is to simply copy the wasm file to your public folder.

Failing that you can check the Vite documentation here: https://vitejs.dev/guide/assets.html

On the @hpcc-js/wasm side take a look at the "wasmFolder" documentation here: https://github.com/hpcc-systems/hpcc-js-wasm#wasmFolder as it will let you override the default location.

1
DharmaTurtle On

Here's what I did to get SQL.js's wasm working with Vite.

SQL.js exposes an API like:

import initSqlJs from "sql.js"

const SQL = await initSqlJs({
  locateFile: file => `https://sql.js.org/dist/${file}`
});

First, I note the wasm file's location as per the instructions:

You can find this file in ./node_modules/sql.js/dist/sql-wasm.wasm after installing sql.js from npm

I then add the following to my package.json scripts:

"postinstall": "cp ../node_modules/.pnpm/node_modules/sql.js/dist/sql-wasm.wasm ./src/assets/sql-wasm.wasm",

Some docs on the npm life cycle operation scripts. Note that cp isn't cross-platform so modify the command for your OS or try this.

I pnpm i to run the postinstall and add the wasm file to .gitignore. Finally, I do:

import sqliteUrl from "../../assets/sql-wasm.wasm?url"

const sql = initSqlJs({
  locateFile: () => sqliteUrl,
}),

Vite docs on Explicit URL Imports.