使用WebPack HMR(热模块更换),无需WebPack-Dev-Server



我用webpack实现了HMR,并且可以正常运行。当我更改已更新的控制台中看到的东西时浏览器?

它通常在我使用webpack-dev-server的客户端工作,但在服务器端,我使用webpack/hot/poll,我需要在每次更改后手动刷新以在浏览器中查看它?

webpack.config.server.js

module.exports = {
  ...
  watch: true,
  target: 'node',
  node: {
    __dirname: true,
    __filename: true
  },
  entry: {
    bundle: [
      'webpack/hot/poll?1000',
      './src/server/devServer'
    ]
  },
  output: {
    path: path.join(__dirname, 'src', 'build'),
    filename: '[name].js'
  },
  resolve: {
    extensions: ['.js', '.jsx'],
    alias: {
      CountdownForm: path.resolve(__dirname, 'src/client/scenes/countdown/components/CountdownForm.jsx'),
     ...
    }
  },
  externals: [nodeExternals({
    whitelist: ['webpack/hot/poll?1000']
  })],
 ...
  plugins: [
    new StartServerPlugin('bundle.js'),
    new webpack.NamedModulesPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new HtmlWebpackPlugin({
      title: 'React Timer',
      template: 'ejs-loader!./src/server/views/index.ejs'
    }),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('development')
      }
    })
  ]
}

devserver

const server = http.createServer(app)
let currentApp = app
server.listen(PORT, () => {
  console.log(`
  Express server is up on port ${PORT}
  Development environment - Webpack HMR active
  `)
})
if (module.hot) {
  module.hot.accept('./index', () => {
    server.removeListener('request', currentApp)
    currentApp = app
    server.on('request', app)
  })
}

webpack-dev-server设置将传输更改的服务器。如果您正在编写自己的服务器应用程序,它将不会是WebPack服务器的客户端。相反,您需要将WebPack添加到服务器中,以便您的客户端可以连接到它并获取更新。为此您需要两件事:

https://github.com/webpack/webpack-dev-middleware
https://github.com/glenjamin/webpack-hot-middleware

首先允许WebPack捆绑您的代码并将其从服务器应用程序提供。第二个允许其将HMR更新传输到客户端。

注意:WebPack-Dev-Server实际上在内部使用WebPack-Dev-Middleware。基本上只是中间件的预配置版本。

相关内容

  • 没有找到相关文章

最新更新