Javascript 如何在Webpack 5中使用Web Workers?
我一直在努力寻找使用Webpack5和typescript的同时使用WebWorkers的最佳方法。我尝试遵循,但是,当我尝试创建Web Worker时,我遇到以下错误:Javascript 如何在Webpack 5中使用Web Workers?,javascript,typescript,webpack,webpack-dev-server,web-worker,Javascript,Typescript,Webpack,Webpack Dev Server,Web Worker,我一直在努力寻找使用Webpack5和typescript的同时使用WebWorkers的最佳方法。我尝试遵循,但是,当我尝试创建Web Worker时,我遇到以下错误: Uncaught DOMException: Worker constructor: Failed to load worker script at "d:\Project\SeamCarving\js\dist0.bundle.js" 我不知道为什么它试图从我的本地系统而不是通过开发服务器访问文件,比如
Uncaught DOMException: Worker constructor: Failed to load worker script at "d:\Project\SeamCarving\js\dist0.bundle.js"
我不知道为什么它试图从我的本地系统而不是通过开发服务器访问文件,比如:http://localhost:8080/js/dist0.bundle.js
代码如下:
if (window.Worker) {
let worker = new Worker(new URL("./image-worker", import.meta.url));
worker.onmessage = function (message) {
return receiveMessage(message);
};
worker.onerror = function (message) {
console.log("ERROR: ", message.error);
console.log(message.message, message.filename, message.lineno);
};
}
webpack.config.js
const path = require('path');
module.exports = {
entry: './js/main.ts',
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
include: path.resolve(__dirname, 'js')
}
]
},
resolve: {
extensions: ['.ts', '.js']
},
devtool: 'source-map',
mode: 'development',
devServer: {
contentBase: path.resolve(__dirname, './'),
publicPath: path.resolve(__dirname, '/js/dist/'),
},
output: {
publicPath: path.resolve(__dirname, "js/dist/"),
filename: "bundle.js",
path: path.resolve(__dirname, 'js/dist'),
}
}
到目前为止,我找到的所有资源都在使用worker loader
,但据我所知,Webpack 5使其过时
查看上的完整项目。我解决了我的问题 不正确输出块:
output: {
publicPath: path.resolve(__dirname, "js/dist/"),
filename: "bundle.js",
path: path.resolve(__dirname, 'js/dist'),
}
output: {
publicPath: "js/dist/",
filename: "bundle.js",
path: path.resolve(__dirname, 'js/dist'),
}
publicPath
在这种情况下设置为使用绝对路径。因此,当我尝试通过服务器运行它时,它将充当文件://
,而不是通过http://
。由于Chrome(我相信大多数现代浏览器)出于安全原因不允许您将本地文件作为脚本加载,所以它阻止了它
最初,我认为使用typescript可能有一些问题,但是,我了解到这只是一个配置错误,导致脚本总是使用绝对值
已纠正输出块:
output: {
publicPath: path.resolve(__dirname, "js/dist/"),
filename: "bundle.js",
path: path.resolve(__dirname, 'js/dist'),
}
output: {
publicPath: "js/dist/",
filename: "bundle.js",
path: path.resolve(__dirname, 'js/dist'),
}
在V5上试用worker loader,从“worker loader!”导入worker/$Path@RobertRowntree谢谢你的建议,但是,我真的想避免在这种情况下使用加载程序,因为正如中所写的那样,Webpack 5中不需要加载程序。@Quinn您是如何使用ts_加载程序的,因为我会得到一个错误new Worker(新URL)('./worker.js',import.meta.url));在这行中,当绑定时,它说可能需要额外的加载器。我可以使用webpack加载器和webpack 4。如何移动到webpack 5