1

我正在尝试让 Webpack 2 + React Hot Loader 工作,但它似乎没有热重载。它可以正确呈现网页,但无论何时我对“App.js”文件进行任何更改,它都不会做任何事情。

webpack.config.json

var path = require('path');
var webpack = require('webpack');
module.exports = {
  entry: {
    'app': [
      'react-hot-loader/patch',
      path.join(__dirname, 'src/main.js')
    ]
  },
  output: {
    path: path.join(__dirname, 'build'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      }
    ]
  }
};

.babelrc

{
  "presets": [
    ["env", {"modules": false}],
    "react"
  ],
  "plugins": [
    "transform-object-rest-spread"
  ]
}

包.json

{
  "main": "main.js",
  "scripts": {
    "dev": "webpack-dev-server --inline --hot"
  },
  "dependencies": {
    "express": "^4.15.2",
    "react": "^15.5.4",
    "react-dom": "^15.5.4"
  },
  "devDependencies": {
    "babel-core": "^6.24.1",
    "babel-loader": "^7.0.0",
    "babel-plugin-transform-object-rest-spread": "^6.23.0",
    "babel-polyfill": "^6.23.0",
    "babel-preset-env": "^1.4.0",
    "babel-preset-react": "^6.24.1",
    "react-hot-loader": "next",
    "webpack": "^2.4.1",
    "webpack-dev-server": "^2.4.4"
  }
}

我通过带有 --hot 和 --inline 标志的 CLI 运行 webpack-dev-server。

main.js

import React from 'react'
import ReactDOM from 'react-dom'
import { AppContainer } from 'react-hot-loader'

import App from './containers/App'

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

render(App)

if(module.hot) {
    module.hot.accept();
}

应用程序.js

import React, { Component } from 'react'

export default class App extends Component {
  render() {
    return (
      <div>
        <div className="container">
          <h1>Testing</h1>
        </div>
      </div>
    )
  }
}

所以为了测试它,我将运行yarn dev并且服务器将启动。一切都会编译,webpack 会输出webpack: Compiled sucessfully. 但是,对 App.js 所做的任何更改都不会重新加载网页。网页本身的控制台仅输出以下内容:

[HMR] Waiting for update signal from WDS...
bundle.js:15580 [WDS] Hot Module Replacement enabled.

我尝试了此处列出的各种方法(https://github.com/webpack/webpack-dev-server/issues/100),但它们似乎都不起作用。

4

1 回答 1

2

在你main.js尝试改变这个:

if(module.hot) {
    module.hot.accept();
}

对此:

  if (module.hot) {
    // Enable Webpack hot module replacement for Component
    module.hot.accept('./containers/App', () => {
      render(App);
    });
  }

您可以在文档中看到更详细的示例

编辑:
根据文档示例,您需要render调用accept.

也许也可以看看webpack 配置

于 2017-04-25T07:59:01.943 回答