vite icon indicating copy to clipboard operation
vite copied to clipboard

Dynamic imports don't work from inlined web worker

Open kot-lex opened this issue 1 year ago • 7 comments
trafficstars

Describe the bug

I'm using an inlined (?worker&inline) web worker that dynamically imports some other libraries. It works well in dev mode but fails in the production build since the filenames are relative which doesn't work with the worker's blob url.

image

Reproduction

https://stackblitz.com/edit/vitejs-vite-2td2he?file=src%2Fworker.ts

Steps to reproduce

  1. Open https://stackblitz.com/edit/vitejs-vite-2td2he?file=src%2Fworker.ts
  2. Open dev tools
  3. Click "send message to worker" button
  4. Check the error message in the console

System Info

System:
    OS: Linux 5.0 undefined
    CPU: (8) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 0 Bytes / 0 Bytes
    Shell: 1.0 - /bin/jsh
  Binaries:
    Node: 18.20.3 - /usr/local/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 10.2.3 - /usr/local/bin/npm
    pnpm: 8.15.6 - /usr/local/bin/pnpm
  npmPackages:
    @vitejs/plugin-react: ^4.3.1 => 4.3.1 
    vite: ^5.3.5 => 5.3.5

Used Package Manager

npm

Logs

No response

Validations

kot-lex avatar Aug 05 '24 16:08 kot-lex

After using inline, the code will be converted to base64 encoding, which leads to the relative path after compilation, which is a wrong way to get it, and I will fix this problem

proc07 avatar Aug 09 '24 03:08 proc07

If the intent is to inline an entire worker without code-splitting, then it's possible to use rollupOptions.output.inlineDynamicImports: true (though probably allowing code-splitting is still useful for inline worker). This is an updated repro https://stackblitz.com/edit/vitejs-vite-b7pvdf?file=vite.config.ts

hi-ogawa avatar Aug 11 '24 06:08 hi-ogawa

@hi-ogawa my goal is to use dynamic imports inside the inline worker without inlining.

kot-lex avatar Aug 11 '24 14:08 kot-lex

@hi-ogawa my goal is to use dynamic imports inside the inline worker without inlining.

@kot-lex Yeah, it's apparent that this pattern is not working and thanks for the reproduction. Btw, can you elaborate more on how it's not ideal to have neither non-inline worker nor fully-bundled inline worker with inlineDynamicImports: true for your actual use cases?

hi-ogawa avatar Aug 12 '24 06:08 hi-ogawa

@hi-ogawa sure:

  1. I serve static from a CDN with a different origin, so my only option is inline worker to avoid CORS issues.
  2. Inside the worker I'm dynamically importing some heavy wasm libraries based on the provided configuration. It would be a huge overhead if I inline all possible variations of those imports.

kot-lex avatar Aug 12 '24 19:08 kot-lex

For your usecase, I'd recommend using this workaround (https://github.com/vitejs/vite/issues/13680#issuecomment-1819274694). IMO the inline worker should inline everything.

sapphi-red avatar Aug 13 '24 07:08 sapphi-red