darionco / rollup-plugin-web-worker-loader

Rollup plugin to load Workers. Supports inlining, dependencies, source maps, NodeJS and browsers.
MIT License
112 stars 31 forks source link

Feature Request: Change where to see worker scripts (loadPath) in runtime #43

Open 0b5vr opened 3 years ago

0b5vr commented 3 years ago

I'm authoring a library using this plugin, and trying to load worker scripts in both development environment and deployed environment (which can have a different codebase, the library is an external dependency and unchangeable though). However it forces me to put the worker scripts onto the very same place of each environment, by using the same loadPath option. Giving an example, I want to put the workers at the root level of my production environment https://example.com/*.worker.js when I'm at https://example.com/page/A (which is achievable by using loadPath: '/'), while in another project I also want to load https://user.github.io/project/dist/*.worker.js or localhost:8080/dist/*.worker.js (which is achievable by using loadPath: '../dist/'). I also don't want to make it inline: true, since the payload is already massive enough and one of my workers needs a support of multibyte chars!

My current solution is to let the loader able to generate the worker factory code with an additional option loadPath, and make it be able to change where to put workers code by purposes. This is what I did (a single commit): https://github.com/FMS-Cat/rollup-plugin-web-worker-loader/commit/6c7118a49590dda4d3f25d5109c6c63b05e1bd9f

However, having an additional option to WorkerOptions might not be cool. I would be happy if you can come up with a better interface and solution.

Thank you for the project, it already helps me so much!

darionco commented 3 years ago

Sorry for the long wait.

I think your solution is sensible but I'd prefer it if we could use something that is future proof, the way it is right now a future change in the Worker API could introduce a name collision, loadPath is a common name after all.

I'd suggest using a Symbol instead, something like:

var loadPathKey = (() => {
    try {
        return Symbol('loadPathKey');
    } catch {
        return '__RPWWL_loadPath__';
    }
})();
export function createURLWorkerFactory(url) {
    var Factory = function WorkerFactory(options) {
        return new Worker((options[loadPathKey] || '') + url, options);
    };
    Factory.loadPathKey = loadPathKey;
}

then it would be used in the code as:


import MyWorker from './some.worker.js';
const worker = new MyWorker({
    [MyWorker.loadPathKey]: '/some/path/to/load/from',
});
0b5vr commented 3 years ago

Mhm, the idea that uses symbols sounds good but the API looks still confusing, comparing how we use the plugin currently......