'JS Cannot load web worker module unless the worker.js is under public/

I would like put my worker.js under the same src/ directory as main.js, which loads the worker. (src/ is parallel to public/) However I got the following error if worker.js is under src/.

//in main.js let worker = new Worker('./worker.js', {type:"module"});

Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

However if I put worker.js under public/ (index.html is under public/), or any directory under public/, everything works fine. Seems like it can only load from public/ aka. http://<my domain>/worker.js , if it is under any directory parallel to public/, then it cannot find it, aka. http://<my domain>/../src/worker.js doesn't work. Am I right on this?

Plus, in worker.js, I cannot import any thing in node_modules/ like what I do for other js files in src/.

I assume these two questions are related. Could you please let me know the solutions?

(I am using worker-plugin, npm, react.)

thank you.



Solution 1:[1]

Based on your entry file, webpack tries to create a dependency tree. So it looks trough all the files that are being imported through a import/require statement, and then it tries to bundle your files into a single bundle. However, it does not happen with the worker constructor. Thus, webpack does not see your worker file as a dependency of your single bundle, and, therefore, it does not bundle it. So, to make this work, you can use a loader in you webpack configuration such as worker-loader (https://v4.webpack.js.org/loaders/worker-loader/), adding a rule in your webpack config file.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Samuel