[英]Webpack HMR for NodeJS with React
我拥有支持 SSR 的应用程序 React + Express(组件初始渲染将在 nodeJS 中完成)。 我想为应用程序实现 HMR。 为此,我使用webpack-hot-middleware
和HotModuleReplacementPlugin
。 它在客户端(浏览器)中按预期工作,但在节点端不工作。
场景:如果我更改了组件中的某些内容,它会立即反映在浏览器中,但如果我重新加载页面,服务器包会返回旧代码并从客户端获取更新。 所以我能够在浏览器中看到闪烁。
客户端 Webpack 配置:
{
entry: {
client: ['@gatsbyjs/webpack-hot-middleware/client', resolvePath(process.cwd(), 'src/client/index.js')]
},
...loaders
plugins: [
new webpack.HotModuleReplacementPlugin(),
new ReactRefreshPlugin({
overlay: {
sockIntegration: 'whm',
},
})
].filter(Boolean)
}
服务器 Webpack 配置:
{
externals: nodeExternals({
allowlist: ['webpack/hot/poll?1000']
}),
target: 'node',
...loaders
entry: {
server: ['webpack/hot/poll?1000', resolvePath(process.cwd(), 'src/server/index.js')]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new NodemonPlugin({
script: path.join('../build', 'server.js')
})
].filter(Boolean)
}
快速代码配置
const compiler = webpack(webpackConfig[0]);
app = express();
app.use(
require('webpack-dev-middleware')(compiler, {
publicPath: webpackConfig[0].output.publicPath,
writeToDisk: true,
serverSideRender: true,
})
);
app.use(
require(`@gatsbyjs/webpack-hot-middleware`)(compiler, {
log: console.log,
path: `/__webpack_hmr`,
heartbeat: 1000,
})
);
一个可能的陷阱是 webpack 配置中的 externals 属性应该是一个数组。
externals: [
nodeExternals({
allowlist: ['webpack/hot/poll?1000']
})
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.