Webpack 2 + React Hot Loader不工作

时间:2017-04-25 07:42:31

标签: reactjs webpack webpack-dev-server react-hot-loader hot-module-replacement

我正在尝试使用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"
  ]
}

的package.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"
  }
}

我正在通过CLI使用--hot和--inline标志运行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();
}

App.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),但似乎都没有。

1 个答案:

答案 0 :(得分: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);
    });
  }

您可以在docs

中看到更详细的示例

编辑:
根据文档示例,您需要在render的回调中调用accept

也可以查看webpack config