vitejs / vite

Next generation frontend tooling. It's fast!
http://vitejs.dev
MIT License
67.09k stars 6.03k forks source link

Prefer worker condition for web-workers #7439

Open stevemk14ebr opened 2 years ago

stevemk14ebr commented 2 years ago

Clear and concise description of the problem

Please refer to the webpack issue here: https://github.com/webpack/webpack/issues/14681. In short, when resolving a module that is used within a webworker, try fields worker or webworker before browser. This helps libraries seperate browser DOM api code from code that also runs in the browser, but does not have DOM api access. To do this now, users must configure like so:

  resolve: {
      conditions: ['worker', 'webworker']
  }

I suggest this be done automatically.

For libraries such as this that need to choose a different conditional export based upon usage. https://github.com/wooorm/parse-entities/issues/19

Suggested solution

First try worker or webworker fields if the module is imported from a webworker.

Alternative

No response

Additional context

No response

Validations

bluwy commented 2 years ago

This makes sense to me since we already have node and browser platform conditions, but maybe we should check worker only (without webworker) to keep it simple, it seems lke webpack does that way too.

stevemk14ebr commented 2 years ago

Sure, I proposed both just because I don't see a standard at the moment or anything and those are the two I'd expect library authors to 'guess' at. One or the other would certainly be better than none!

poyoho commented 2 years ago

this mean is if work in node, we should export node worker?

const worker = require('worker_threads');
export default new worker.Worker(...)
bluwy commented 2 years ago

I think if a package export node workers, it would be nested within a node and worker condition, if they choose so.

cesutherland commented 1 year ago

Here's an example package where I ran into this issue: https://github.com/wooorm/decode-named-character-reference/blob/main/package.json#L32-L40

Configuring resolve.conditions as described above sorted the worker for me (https://vitejs.dev/config/shared-options.html#resolve-conditions), but then both WebWorker and browser assets are built using the worker condition if that's available.

Is there any solution for that, aside from using a separate vite config for the worker?

davidmyersdev commented 4 weeks ago

I've run into the same problem described by @cesutherland. Is it possible that resolve.conditions could be made unique per environment? Is this something the new Environment API might help solve?