I've inherited a task to upgrade from Webpack 4 to 5 and have the following custom plugin that works with Webpack 4 but obviously doesn't with Webpack 5 due to the change to using hooks. I am pretty new to all this and am struggling to rewrite the following to work with Webpack 5. Any help would be grateful.
// When webpack compiles, it detects and inserts the host and the port for sockjs to use.
// by default it sets 8080,
// which still doesn't help as our devproxy is only listing to port 80 and 443.
// Our solution is to use webpack's plugin api to inject the desired host during compilation.
// The plugin only applies the host change when the file 'webpack-dev-server/client/index.js' is being compiled.
// It works by redefining the `__resourceQuery` variable that is set by webpack to
// inject the true host
class InjectDevServerHostnamePlugin {
getQuery(request) {
const i = request.indexOf('?')
return request.indexOf('?') < 0 ? '' : request.substr(i)
}
apply(compiler) {
const plugin = this
compiler.plugin('compilation', (compilation, params) => {
params.normalModuleFactory.plugin('parser', (parser) => {
// eslint-disable-next-line func-names
parser.plugin('expression __resourceQuery', function () {
if (!this.state.module) return
if (this.state.module.resource.match('webpack-dev-server/client/index.js')) {
// eslint-disable-next-line no-console
console.log('fixing webpack-dev-server location for sock-js')
this.state.current.addVariable('__resourceQuery', JSON.stringify(plugin.getQuery(this.state.module.resource).replace('http://localhost:4999', 'https://app.companyname.dev')))
}
// eslint-disable-next-line consistent-return
return true
})
})
})
}
}
module.exports = InjectDevServerHostnamePlugin