Posted on
Invoking Web Worker as a module
Uau, I didn't know about that but all indicates that it is possible to load web worker directly as a module.
Before, I was loading the script via HTTP passing the public path, note that I am using a React application with Vite.
Old example:
I didn't like this way of loading web workers because I was forced to write it as a javascript file, and I couldn't import other modules inside that. Take a look:
Web Worker script:public/get-merchant-ids-from-csv.js
self.onmessage=functionhandleMessageFromMain(message){/** * @type {File} */constfile=message.data;constresult=newFileReader();result.readAsText(file);result.onloadend=function(){constmerchantIds=extractValues(result.result);self.postMessage(merchantIds);};};functionextractValues(result){const[,...rows]=result.split('\n');constvalues=rows.map((row)=>{constitems=row.split(',');returnitems.reduce((_,item,index)=>{returnString(item).trim();},[]);});returnvalues;}
Invoking the web worker from the public directory
// NOTE: In my case I needed to specify the base URL, but in most of cases you can write the URL starting with "/"constGET_MERCHANT_IDS_FROM_FILE_WORKER=`${BASE_URL}/get-merchant-ids-from-csv.js`;constworker=newWorker(GET_MERCHANT_IDS_FROM_FILE_WORKER);
Prefered way example:
Web worker script:src/modules/shared/workers/get-merchant-ids-from-csv.ts
Note that it is a typescript now
self.onmessage=functionhandleMessageFromMain(message:MessageEvent<File>){constfile=message.data;constresult=newFileReader();result.readAsText(file);result.onloadend=function(){constmerchantIds=extractValues(String(result.result));self.postMessage(merchantIds);};};functionextractValues(result:string){const[,...rows]=result.split('\n').map((row)=>row.trim());returnrows;}
The new way of importing the web worker:
constworker=newWorker(newURL('../../shared/workers/get-merchant-ids-from-csv.ts',import.meta.url,),{type:'module',},);
Now, it is possible to import other modules, and independent of the place where the script is located, we can inform the path and import it. Note that it is important to pass as a second parameter the base URLimport.meta.url
(exposed by vite build system)
Top comments(1)
For further actions, you may consider blocking this person and/orreporting abuse