Search code examples
javascriptweb-workernetlify

Trouble loading modules in a JavaScript web worker


I've got a web worker primes.js that I want to break up into smaller files. Not having any luck.

First thing I did was to load the Worker as type:module:

worker.current = new Worker('primes.js', {type: module})

Executing this worker works okay.

Next I move some code from primes.js to primeTest.js and export a function.

...
export function primeTest {...}
...

I then add an import statement to primes.js:

import primeTest from './primeTest'

However, this results in a MIME error, stating that primeTest is of type 'text/HTML'.

If I change the import statement to

import primeTest from './primeTest.js'

the MIME error goes away, no console error appears, but the app hangs when the worker is called. I put a debugger statement in the web worker, but it's not triggered.

I'm using Netlify's build/deploy scripts, if that matters.


Solution

  • You have used named export:

    export function primeTest {...}
    

    So you have use named import

    import { primeTest } from './primeTest.js'
    

    You can also use default export:

    export default function primeTest {...}
    

    And import default

    import primeTest from './primeTest.js'