DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script failed to load

Viewed 534

I am trying to use a web worker to compute some data that takes some time. It is in a React app that has not been ejected. I have pasted a bunch of code in case it helps in figuring the problem but the main problem I am having is that I am not able to import modules into the worker. Below is my worker and how it is invoked.

CalendarEvents.worker.js

importScripts('ImportWorkerModules.js')

onmessage = ({ data: { alarms, startDate, endDate, calendarView } }) => {
  const getEventsForAlarmsInRange = self.AlarmUtils.getEventsForAlarmsInRange
  const events = getEventsForAlarmsInRange(
    alarms,
    startDate,
    endDate,
    calendarView
  )
  postMessage({
    events
  })
}

ImportWorkerModules

// my-app-shared is my own package contained in a monorepo that contains shared business logic between the mobile app and the web app.
import { AlarmUtils } from 'my-app-shared'

WebWorkerUtils.js

import CalendarEventsWorker from 'worker-loader!./CalendarEvents.worker.js'

const WebUtils = (function () {
  const getEventsForCalendar = (alarms, startDate, endDate, calendarView) => {
    const promise = new Promise(resolve => {
      const worker = new CalendarEventsWorker()
      worker.postMessage({
        alarms,
        startDate,
        endDate,
        calendarView
      })
      worker.onmessage = ({ data: { events } }) => {
        resolve(events)
      }
    })
    return promise
  }

  return {
    getEventsForCalendar
  }
})()

export default WebUtils

This is how it is invoked:

  useEffect(() => {
    WebWorkerUtils.getEventsForCalendar(
      alarmsToConsider,
      dateRange.start,
      dateRange.end,
      calendarView
    ).then(events => {
      events.forEach(event => {
        const alarmCategory = AlarmUtils.getAlarmCategoryForAlarm(
          alarmCategories,
          event.id
        )
        event.category = alarmCategory
      })
      setEvents(events)
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    dateRange,
    allAlarms,
    alarmCategories,
    categorizedAlarmView,
    currentlySelectedAlarmCategoryId
  ])

I see the following error on Chrome Developer Tools: DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'http://localhost:3000/static/js/ImportWorkerModules.js' failed to load.

Chrome Developer Tools Error

How can I fix this error? I have tried searching for possible solutions for this error on the web but haven't found anything concrete.

0 Answers
Related