'Webpack 5 Custom Plugin Upgrade
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
Solution 1:[1]
I was struggling with exactly this same issue and stumbled across your unanswered post...
You can use Webpack 5's webSocketURL to do exactly what you're after with no extra code/plugins required.
Few examples here:
Hope that helps!
EDIT: as suggested in comments, some inline examples copied/pasted from the docs in case Webpack's documentation links go dead - both examples below can be used in webpack.config.js
module.exports = {
//...
devServer: {
client: {
webSocketURL: 'ws://0.0.0.0:8080/ws',
},
},
};
... or:
module.exports = {
//...
devServer: {
client: {
webSocketURL: {
hostname: '0.0.0.0',
pathname: '/ws',
password: 'dev-server',
port: 8080,
protocol: 'ws',
username: 'webpack',
},
},
},
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
