javascriptviteweb-worker

Loading a worker script at build time in a Vite project


Is it possible to create define a web worker such that it does not have to load from an external file during runtime in a vite project? I am building a browser that depends on a web worker file and I want to build into one index.js asset file that can be used outside of the project. The problem is that I will need to deploy the index.js asset file along with the web worker file since it is being loaded through the URL. Is there away to allow the web worker's logic to be included into the final index.js file such that it can be defined and loaded from within the same index.js asset file?


Solution

  • I have just found another solution to this problem using vite's inline worker import: https://vitejs.dev/guide/features.html#import-with-query-suffixes

    This way, vite can compile the worker file and add it automatically into the final bundle asset.