电子+ React + Webpack开发中间件+ hmr-刷新整个页面,而不是热重载

时间:2018-12-11 16:12:26

标签: reactjs webpack electron hot-module-replacement

在我的一生中,我似乎无法重新开始工作。有人有什么想法吗?我在控制台中看到的是“ [HMR]已连接”,但是当我对react组件进行更改时,整个页面都会刷新。 我了解我应该遵循以下原则:

[HMR] bundle rebuilding
[HMR] bundle rebuilt in 5269ms

.....

但是我什么都看不到。

这是我的配置:

server.js

var path = require('path')
var webpack = require('webpack')
var express = require('express')
var config = require('./webpack.config')

var app = express()
var compiler = webpack(config)

app.use(
  require('webpack-dev-middleware')(compiler, {
    publicPath: config.output.publicPath
  })
)

app.use(require('webpack-hot-middleware')(compiler, {
  heartbeat: 10 * 1000
}))

app.get('*', function(req, res) {
  res.sendFile(path.join(__dirname, 'index.html'))
})

const PORT = 8080
app.listen(PORT, function(err) {
  if (err) {
    return console.error(err)
  }
  console.log(`Listening at http://localhost:${PORT}/`)
})

webpack.config.js

const path = require('path')
const webpack = require('webpack')

module.exports = {
  mode: 'development',
  entry: [
    'react-hot-loader/patch',
    'webpack-hot-middleware/client?path=http://localhost:8080/__webpack_hmr',
    'babel-polyfill',
    './src/index.js'
  ],
  output: {
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/dist/',
    filename: 'bundle.js'
  },
  target: 'electron-main',
  plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.ExternalsPlugin('commonjs', ['electron']) ],
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/, // include .js files
        exclude: /node_modules/, // exclude any and all files in the node_modules folder
        loader: require.resolve('babel-loader'),
        include: path.join(__dirname, 'src')
      },
      {
        test: /\.css$/,
        use: [{loader: 'style-loader'}, {loader: 'css-loader'}]
      }
    ]
  },
  externals: ['electron', 'fs']
}

src / index.js

import React from 'react'
import ReactDOM from "react-dom"
import {AppContainer} from 'react-hot-loader'
import App from './app'

const renderApp = Component => {
  ReactDOM.render(
    <AppContainer>
      <App />
    </AppContainer>,
    document.getElementById("root")
  )
}


renderApp(App)

if (module.hot) {
  module.hot.accept('./app.js', () => {
    const nextRootContainer = require('./app').default
    renderApp(nextRootContainer)
  })
}

.babelrc

{
  "presets": ["@babel/preset-env", "@babel/preset-react", "@babel/preset-flow"],
  "plugins": [
    ["transform-class-properties", { "loose": true }],
    "react-hot-loader/babel"
  ]
}

欢迎任何建议!

0 个答案:

没有答案