-
-
Notifications
You must be signed in to change notification settings - Fork 7.2k
Description
Description
Currently, the wasm plugin usually get the .wasm
file using fetch
. This approach doesn't work in SSR. Even if fetch
were available, fetching a relative path would not work. This results in errors such as ERR_INVALID_URL
when in SSR.
Suggested solution
By adding an extra if cause to the wasm helper, we could check the import.meta.env.SSR
to see if we're in SSR mode. If we are, then we could load the file from disk instead of fetching it over the network. Something like this:
const wasmHelper = async (opts = {}, url: string) => {
if (url.startsWith('data:')) {
// load from inline base64 string
} else if (import.meta.env.SSR) {
// load from disk
} else {
// fetch over the network
}
}
However, there might be problems to using import.meta
that I'm not aware of. It seems to work fine for me when I'm testing it, but I've only tested it with SvelteKit.
If using the SSR environment variable isn't an option, then we could of course use some typeof window === "undefined"
or perhaps process
would be better. But there might be several pitfalls with that, mainly other plugins that polyfills window, process or whatever thing we might use. Perhaps a better approach would be to add the file system logic in a .catch
block on the fetch
itself, something like:
const response = await fetch(url).catch(async (err) => {
if (!(err && err.code === "ERR_INVALID_URL")) throw err;
// load from disk and return new Response(fileBuffer)
}
Another problem with loading from disk is that the URL provided is a URL, and not a file path. Fortunately it contains the file path, but I'm not sure if that would always be the case, or if it might be a better way of resolving the file path. Using the provided url
string, it is possible to decode the path using something like url.replace("/@fs", "")
.
Alternative
A workaround is to use another wasm plugin. I haven't found a vite wasm plugin that works with SSR, so currently we have created our own just to make it work (using the import.meta.env.SSR
technique mentioned above). That works great with SvelteKit, but might not work with everything. If it's of any interest to someone else, just let me know and I can see if we could push it to NPM.
I've also raised an issue (Menci/vite-plugin-wasm#4) in the vite-pugin-wasm repo to make SSR work, but it has some challenges regarding ESM to utilize import.meta
.
Additional context
No response
Validations
- Follow our Code of Conduct
- Read the Contributing Guidelines.
- Read the docs.
- Check that there isn't already an issue that request the same feature to avoid creating a duplicate.