Open alisman opened 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.
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);
});
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):
Any idea what I'm doing wrong?
You need to use a browser that supports modules-in-Workers. I believe Chrome Canary would let you try that out.
So standard Chrome doesn't support it?
@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!
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?