压缩ES6模块后WebWorker运行失败问题求助
Hey there, I’ve run into this exact kind of minification quirk with Web Worker libraries before—totally frustrating when uncompressed code works perfectly but breaks after build! The core problem here is that UglifyJsPlugin is renaming the self parameter in your worker’s export function to e during compression, but in the Worker execution context, self is a reserved global variable pointing to the Worker’s own scope. When the minified code tries to use e, it can’t resolve it because the Worker isn’t being invoked with that argument correctly.
Here are three solid fixes you can try, ordered by how future-proof they are:
Swap UglifyJsPlugin for TerserPlugin
UglifyJs is no longer actively maintained and has known gaps handling modern JS features like Web Workers. Terser is its official successor and handles Worker scope variables way better. Update your Webpack config to use it instead:const TerserPlugin = require('terser-webpack-plugin'); module.exports = { optimization: { minimizer: [new TerserPlugin()] } };Force UglifyJs to preserve the
selfvariable name
If you need to stick with UglifyJsPlugin for now, configure it to avoid renaming theselfparameter. Add themangle.reservedoption to your plugin setup:const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); module.exports = { optimization: { minimizer: [ new UglifyJsPlugin({ uglifyOptions: { mangle: { reserved: ['self'] } } }) ] } };Rename the worker parameter (if you can modify the code)
If you have access to the worker’s source code (or can fork the library), rename theselfparameter to something that won’t clash with the global Workerself—likeworkerScope:module.exports = function (workerScope) { // Update your worker logic to use workerScope instead of self };
Any of these should resolve the ReferenceError you’re seeing. The TerserPlugin switch is the best long-term fix since it’s actively maintained and handles edge cases like this out of the box.
内容的提问来源于stack exchange,提问作者Ed Williams

