让 webpack 热更新在我的同构网络应用程序中正常工作

Getting webpack hot updating to work correctly in my isomorphic web app

我正在创建一个带有 node/express 后端和反应前端的网络应用程序。我得到了(我认为)大部分内容 运行,但是让浏览器执行热刷新的最后一步没有按预期工作。我将在这里尝试 post 所有相关设置。如果您需要其他任何东西来找出我在哪里做错了,请告诉我:

我用 node ./server/index.js

启动我的应用程序

webpack.config.js var path = require('path'); var webpack = require('webpack');

let webpackConfig = {
    name: 'server',
    output: {
        path: path.join(__dirname, 'dist'),
        filename: 'bundle.js',
        publicPath: '/dist/',
    },
    resolve: {
      extensions: [
        '', '.js', '.jsx', '.json'
      ]
    },
    module: {
        loaders: [
            { 
                test: /\.(js|jsx)$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query:{
                    presets: ['es2015', 'react', 'stage-2']
                }
            },
            {
                test:  /\.json$/, 
                loader: 'json-loader'
            }
        ]
    },
    entry: [
        'webpack-hot-middleware/client',
        './app/client/client.jsx'   
    ],
    plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify('production')
            }
        }),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoErrorsPlugin()
    ]   
};
export default webpackConfig;

index.js 只包括 'babel-register' 和 'server.js'

server/server.js 从 'webpack' 导入 webpack; 从 '../webpack.config' 导入 webpackConfig; 从 'webpack-dev-middleware' 导入 webpackDevMiddleware; 从 'webpack-hot-middleware';

导入 webpackHotMiddleware
import express from 'express';

const app = express();
const renderPage = () => {
    return `
            <!doctype html>
            <html>
            <head>
                <title>Brewing Day</title>
                <meta charset='utf-8'>
            </head>
            <body>
                <h1>Hello from server.js!!</h1>
                <div id='root'></div>
                <script src='/dist/bundle.js'></script>
            </body>
            </html>
            `;
};

const compiler = webpack(webpackConfig);
app.use(webpackDevMiddleware(compiler, {
    noInfo: true,
    publicPath: webpackConfig.output.publicPath })
);
app.use(webpackHotMiddleware(compiler));

app.use((req, res, next) => {
  res.status(200).end(renderPage());
});

const server = app.listen(3005, () => {
    const host = server.address().address;
    const port = server.address().port;
    console.log(`Listening at http://${host}:${port}`);
})

export default server;

app/client/client.jsx 是 webpack 配置中的入口点:

import React from 'react';
import ReactDOM from 'react-dom';
import Application from '../components/application.jsx';

window.addEventListener('load', () => {
    ReactDOM.render(<Application />, document.getElementById('root')
    );
});

在控制台中,当我启动它时,它列出以下行:

webpack built cc1194a11614a3ba54a3 in 730ms

当我对包含 rect 组件的 client.jsxapplication.jsx 进行更改时,我在控制台中得到两条新行:

webpack building...
webpack built 8d340a8853d3cfe9478d in 195ms

到目前为止,一切顺利!

但是,在浏览器中,它不会更新并在控制台中给出以下警告:

[HMR] The following modules couldn't be hot updated: (Full reload needed)
This is usually because the modules which have changed (and their parents) do not know how to hot reload themselves. See http://webpack.github.io/docs/hot-module-replacement-with-webpack.html for more details.
[HMR]  - ./app/components/application.jsx

我尝试随机添加 module.hot.accept()application.jsx。这消除了警告,但如果不按 F5 并重新加载浏览器仍然没有更新。

知道我在这里遗漏了什么吗?我见过另一个设置几乎与我的设置类似的示例,其中无需任何 module.hot.accept() 调用即可工作,但我看不出我的设置与其他设置有何不同。

我们将不胜感激。

经过大量挖掘,我找到了问题的答案。我正在像这样创建我的基础 React "class":

class Application = () => {
  return (
    <div id="maincontent">
      <MainMenu />
      <ScreenContents />          
    </div>
  )
};

即使 React 支持,HMR 也不支持。

我必须像这样明确地创建我的 class:

class Application extends React.Component{
  render (){
    return (
      <div id="maincontent">
        <MainMenu />
        <ScreenContents /> 
      </div>
    );
  }
};

然后 HMR 工作正常:)

编辑:根据@akoskm 的评论,似乎 webpack 配置文件中的 babel 配置也可能是一个问题。所以这里是相关部分:

babel 设置

var babelSettings = {
    presets: ['react', 'es2015', 'stage-2'],
    env: {
        development: {
            plugins: [
                ['react-transform', {
                    transforms: [
                        { 
                            transform: 'react-transform-hmr',
                            imports: [ 'react' ],
                            locals: [ 'module' ]
                        }
                    ]
                }]
            ]
        }
    }
};

预设和环境内容对您来说可能不完全相同,但 react-transform 内容是这里的重要部分。

装载机

{ 
    test: /\.(js|jsx)$/,
    loaders: ['babel?' + JSON.stringify(babelSettings)],
    exclude: /node_modules/
}