developit / workerize

🏗️ Run a module in a Web Worker.
https://github.com/developit/workerize-loader
4.35k stars 91 forks source link

External deps #9

Open alisman opened 6 years ago

alisman commented 6 years ago

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?

developit commented 6 years ago

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 commented 6 years ago

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);
});
arizonatribe commented 6 years ago

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?

developit commented 6 years ago

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

arizonatribe commented 6 years ago

So standard Chrome doesn't support it?

jpvalenciag commented 6 years ago

@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!