Hi, I'm trying to use web workers with nextron (+typescript), but I haven't found any easy way yet.
I tried installing @zeit/next-workers and worker-loader.
Also, needed to set some global typings as explained in the webpack configuration (_Integrating with TypeScript_):
// typings/custom.d.ts
declare module 'worker-loader!*' {
class WebpackWorker extends Worker {
constructor();
}
export default WebpackWorker;
}
Trying to include the worker...
import TestWorker from 'worker-loader!../../test.worker';
//...
const worker = new TestWorker();
worker.postMessage({ foo: 'bar' });
worker.addEventListener('message', (event) => console.log(event));
compiles ok, but when trying to execute that code, it results in a 404
GET http://localhost:8888/_next/c00177f2ed8cf0fa8620.worker.js 404 (Not Found)
Funny thing here is, getting into the .next directory, I can see it...
$ ls nextron/renderer/.next/c00177f2ed8cf0fa8620.worker.js
c00177f2ed8cf0fa8620.worker.js
I'm not sure if it's the compilation, next internals, nextron's bootstrapped environment or what, but I can use some help here :)
I'm using Next and I have the same problem. For some reason when importing the worker using inlined worker-loader, the outputPath is lost. I don't know why this happens and I'm not sure if it's an issue of next-workers orworker-loader.
The way I managed to make this work is by adding the name as a query including the outputPath:
// index.d.ts
declare module 'worker-loader?name=static/[hash].worker.js!*' {
聽聽 class WebpackWorker extends Worker {
聽聽聽聽 public constructor();
聽聽 }
聽聽 export default WebpackWorker;
}
// index.ts
import SomeWorker from 'worker-loader?name=static/[hash].worker.js!./some.worker';
Maybe this could help you.
Copy and paste the source like this:
// in the next.config.js
module.exports = {
webpack: config => {
config.module.rules.push({
test: /\.worker\.js$/,
loader: 'worker-loader',
options: {
name: 'static/[hash].worker.js',
publicPath: '/_next/'
}
})
config.output.globalObject = `(typeof self !== 'undefined' ? self : this)`
return config
}
}
Solves the problem.
(But I don't know why.)
Same Issue, that didn't solve my issue
const withPlugins = require('next-compose-plugins');
const withCSS = require('@zeit/next-css');
const withWorkers = require('@zeit/next-workers');
const nextConfig = {
webpack: (config) => {
config.module.rules.push({
test: /\.worker\.js$/,
loader: 'worker-loader',
options: {
name: 'static/[hash].worker.js',
publicPath: '/_next/'
}
});
config.output.globalObject = `(typeof self !== 'undefined' ? self : this)`;
return config;
}
};
module.exports = withPlugins(
[
[withCSS],
[
withWorkers,
{
workerLoaderOptions: { inline: true }
}
]
],
nextConfig
);
Getting 404 everytime
Most helpful comment
Same Issue, that didn't solve my issue
Getting 404 everytime