workerize icon indicating copy to clipboard operation
workerize copied to clipboard

External deps

Open alisman opened this issue 7 years ago • 6 comments

We very often want to use libraries like lodash in compute intensive routines that would be good to run in workers. Have you thought about how to solve this problem?

alisman avatar Jan 12 '18 17:01 alisman

Yup, that's what workerize-loader is for.

Alternatively, it would be pretty easy to add { type: 'module' } to the Worker instance here, which would enable ES Module imports in modern browsers.

developit avatar Jan 13 '18 20:01 developit

Using ES Modules is now supported in 0.1.5.

It works like this:

import workerize from 'workerize';

const worker = workerize(`
  import fetchJson from './fetcher'

  export function get(url) {
    return fetchJson(url)
  }
`, { type: 'module' });

worker.get('./some-url').then( data => {
  console.log('Response: ', data);
});

developit avatar Jan 19 '18 15:01 developit

I'm receiving an error when I attempt to implement this feature.

To troubleshoot, I rolled back to version 0.1.5 and attempted to directly mimic the example code:

// fetcher
function fetchJson(url, config = {}) {
    return fetch(url, {
        ...config,
        headers: {
            ...(config.headers || {}),
            'Content-Type': 'application/json'
        }
    }).then(response => response.json())
}

export default fetchJson

And implementing it in a worker:

const worker = workerize(`
    import fetchJson from './fetcher'

    export function get(url) {
        return fetchJson(url)
    }
`, {type: 'module'})

worker.get('https://jsonplaceholder.typicode.com/posts/1').then(data => {
    console.log('Response: ', data)
})

Yields the following error (also logging the worker to the console):

screen shot 2018-05-24 at 10 16 02 am screen shot 2018-05-24 at 10 22 27 am

Any idea what I'm doing wrong?

arizonatribe avatar May 24 '18 17:05 arizonatribe

You need to use a browser that supports modules-in-Workers. I believe Chrome Canary would let you try that out.

developit avatar Jun 01 '18 22:06 developit

So standard Chrome doesn't support it?

arizonatribe avatar Jun 03 '18 17:06 arizonatribe

@developit I'm trying to implement this but I'm getting an error in Chrome:

TypeError: Failed to construct 'Worker': Module scripts are not supported on DedicatedWorker yet.

So yeah, maybe standard Chrome doesn't support this yet. But on Firefox I'm getting a different error:

SyntaxError: import declarations may only appear at top level of a module

Do you know what could be causing it? Thanks!

jpvalenciag avatar Jul 05 '18 20:07 jpvalenciag