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.url for 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

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 3
  • Comments: 22 (9 by maintainers)

Commits related to this issue

Most upvoted comments

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:

client.ts:288 Uncaught (in promise) ReferenceError: document is not defined
    at hasErrorOverlay (client.ts:288:3)
    at handleMessage (client.ts:150:28)
    at WebSocket.<anonymous> (client.ts:91:5)

Adding self.document = {querySelectorAll(){return []}} to the web worker silences the error.

for me this wasn’t enough, since the subsequent code needed document.baseURI to create an URL, so I added the following to my shim.mts:

// @ts-ignore
self.document = {
    baseURI: location.origin
}

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 of document by the bundler so it still breaks for me. Inlining is also not an option