Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use import.meta in worker got error: document is not defined #4646

Closed
7 tasks done
ahaoboy opened this issue Aug 18, 2021 · 10 comments · Fixed by #7464
Closed
7 tasks done

use import.meta in worker got error: document is not defined #4646

ahaoboy opened this issue Aug 18, 2021 · 10 comments · Fixed by #7464

Comments

@ahaoboy
Copy link

ahaoboy commented Aug 18, 2021

Describe the bug

use import.meta in worker, in dev mode is ok, but after build got the error

 // source 
console.log(import.meta.url);

// after build:
console.log(document.currentScript && document.currentScript.src || new URL("worker.js",document.baseURI).href)

document doesn't exist in web worker

Reproduction

create worker in main.js

import Worker from "./worker?worker";
const w = new Worker();
w.postMessage(1);

worker.js

self.addEventListener("message", () => {
  console.log(import.meta.url);
});

System Info

System:
    OS: Windows 10 10.0.19043
    CPU: (16) x64 11th Gen Intel(R) Core(TM) i7-11800H @ 2.30GHz
    Memory: 13.14 GB / 31.67 GB
  Binaries:
    Node: 16.4.2 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.10 - ~\AppData\Roaming\npm\yarn.CMD
    npm: 7.19.1 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Edge: Spartan (44.19041.1023.0), Chromium (92.0.902.73)
    Internet Explorer: 11.0.19041.906
  npmPackages:
    @vitejs/plugin-vue: ^1.3.0 => 1.4.0
    vite: ^2.4.4 => 2.4.4

Used Package Manager

pnpm

Logs

No response

Validations

@CHOYSEN
Copy link
Contributor

CHOYSEN commented Aug 20, 2021

I think this issue relate with https://github.com/vitejs/vite/pull/2494/files#r598314757 in #2494.

@mathe42
Copy link
Contributor

mathe42 commented Aug 25, 2021

I think this is a problem / feature of rollup see https://www.rollupjs.org/guide/en/#resolveimportmeta

In ES modules, import.meta is an object and import.meta.url contains the URL of the current module, e.g. http://server.net/bundle.js for browsers or file:///path/to/bundle.js in Node.

By default for formats other than ES modules, Rollup replaces import.meta.url with code that attempts to match this behaviour by returning the dynamic URL of the current chunk. Note that all formats except CommonJS and UMD assume that they run in a browser environment where URL and document are available.

So we need to tell rollup to handle import.meta.url different in modules.

I will work on a solution on that for a plugin with workers that I wrote and post it here if I found something!

@mathe42
Copy link
Contributor

mathe42 commented Aug 25, 2021

Simple plugin where config is the resolved vite config

{
  name: "worker-env",
  resolveImportMeta(prop, ctx) {
    if (prop !== "url") return null;

    return `new URL('${ctx.chunkId}', location.origin + '${config.base[0] == '/' ? '' : '/'}${config.base}').href`;
  },
}

When this is added to the plugin-list here:
https://github.com/vitejs/vite/blob/main/packages/vite/src/node/plugins/worker.ts#L59

This would fix this problem.

@JarekToro
Copy link

This seems to have already been addressed in rollup. rollup/rollup#4186
Can we "rollup" that fix into vite? 🥁 🐍

@mathe42
Copy link
Contributor

mathe42 commented Dec 18, 2021

@JarekToro Is this still a problem? That fix is in the current rollup version used by vite fixed... So if that was I thought was the problem this should be fixed now.

@JarekToro
Copy link

JarekToro commented Dec 18, 2021

Update:

The core problem is actually simpler then what is presented here. See #4646 (comment)

More complicated example

So it seems to be a tangential problem. I created a stack blitz to demonstrate the issue.

https://stackblitz.com/edit/vitejs-vite-yqbzxq?file=lib/assets/test.worker.81214889.js

Seems that when reference import.meta from an imported script into a worker it fails to remove the document references

Should check the stack blitz for real example but in short

index.ts

import worker from './test.worker?worker';
console.log(new worker());

test.worker.ts

import './worker_import_script';

addEventListener(
  'message',
  function (e: any) {
      console.log(e)
  },
  false
);
postMessage({ ready: true });

worker_import_script.ts

// This right here adds document references when bundled into the worker.
var _scriptDir = import.meta.url; 
console.log(_scriptDir);
// This right here actually works fine
const wasmBinaryFile = new URL('test.wasm', import.meta.url).toString();
console.log(wasmBinaryFile);

output

(function(){"use strict";
var e=document.currentScript&&document.currentScript.src||new URL("test.worker.js",document.baseURI).href;
console.log(e);
// ...etc

@JarekToro
Copy link

EDIT: Problem can be simplified further. All that is actually needed is this code in a worker.
test.worker.ts

var _scriptDir = import.meta.url; 
console.log(_scriptDir);

As it gets converted to

(function(){"use strict";var r=document.currentScript&&document.currentScript.src||new URL("test.worker.js",document.baseURI).href;console.log(r)})();

@mathe42
Copy link
Contributor

mathe42 commented Dec 18, 2021

As long this is not fixed you can try https://github.com/mathe42/vite-plugin-worker

@JarekToro
Copy link

Awesome thanks

@bluwy
Copy link
Member

bluwy commented Mar 14, 2022

Still reproducible in Vite 2.9.0-beta.2

@github-actions github-actions bot locked and limited conversation to collaborators Apr 11, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

6 participants