vite: "document" is not defined for xxxx.wasm?url
Describe the bug
Hi there,
the following error is fired when I use latest version 3.0.9 to compile the following code in production mode:
import xxxx from “…/…/xxx.wasm?url”;
The error is as follows. “document” is not defined
So I switch back to old version 2.9.x and the error disappear
After some investigation, I found it is caused by the changeset:
- fix: avoid using
import.meta.urlfor relative assets if output is not ESM (fixes #9297) (#9381)
The following code doesn’t check document variable:
const getRelativeUrlFromDocument = (relativePath: string, umd = false) =>
getResolveUrl(
'${relativePath}', ${ umd ? typeof document === ‘undefined’ ? location.href : : '' }document.currentScript && document.currentScript.src || document.baseURI
)
So I suggest to add a simple “typeof document !== ‘undefined’” in the last sentence.
Reproduction
https://stackblitz.com/edit/vitejs-vite-85cthg?file=vite.config.js
run “npm run build” then “vite preview”
System Info
"document" is not defined
Used Package Manager
yarn
Logs
No response
Validations
- Follow our Code of Conduct
- Read the Contributing Guidelines.
- Read the docs.
- Check that there isn’t already an issue that reports the same bug to avoid creating a duplicate.
- Make sure this is a Vite issue and not a framework-specific issue. For example, if it’s a Vue SFC related bug, it should likely be reported to vuejs/core instead.
- Check that this is a concrete bug. For Q&A open a GitHub Discussion or join our Discord Chat Server.
- The provided reproduction is a minimal reproducible example of the bug.
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Reactions: 3
- Comments: 22 (9 by maintainers)
Commits related to this issue
- Fix loading of the LSP worker script in the online editor The update to vite 4 triggered the vite 3 bug vitejs/vite#9879 for us, where the wasm-pack generated .js is included as iife and therefore th... — committed to slint-ui/slint by tronical a year ago
- workaround for vite bug -- https://github.com/vitejs/vite/issues/9879 — committed to vlcn-io/live-examples by tantaman a year ago
I have a similar error, using vite, svelte, web worker (via comlink).
When I edit the svelte component (so it seems to be caused by HMR) I see the error below:
Adding
self.document = {querySelectorAll(){return []}}to the web worker silences the error.for me this wasn’t enough, since the subsequent code needed
document.baseURIto create an URL, so I added the following to myshim.mts:Oh, I’m sorry. It was slightly diffrent kind of bug. To describe it, if you “import” something in web worker, some bug like this still happens. I’ll submit another issue after making reproduction on stackblitz.
Are there any updates for this? The
self.document = {querySelectorAll(){return []}}is put after the usage ofdocumentby the bundler so it still breaks for me. Inlining is also not an option