Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Pedro Oliveira
Pedro Oliveira

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;}
Enter fullscreen modeExit fullscreen mode

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);
Enter fullscreen modeExit fullscreen mode

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;}
Enter fullscreen modeExit fullscreen mode

The new way of importing the web worker:

constworker=newWorker(newURL('../../shared/workers/get-merchant-ids-from-csv.ts',import.meta.url,),{type:'module',},);
Enter fullscreen modeExit fullscreen mode

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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
sohaibs_amir_ea168b94720 profile image
Sohaib’s Amir
  • Joined

I am trying to invoke worker in my react native web app bundled using metro. I am trying to do it like the way you did but it fails. Maybe you can help me on this matter. Thanks in advance

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I am sharing pieces of my experience.
  • Location
    Brazil, São Paulo
  • Pronouns
    He/Him
  • Work
    Frontend developer at iFood
  • Joined

More fromPedro Oliveira

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp