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

标签 node.js express webpack webpack-dev-server webpack-hmr

我正在创建一个带有 Node/快速后端和 react 前端的网络应用程序。我(我认为)大部分都启动并运行了,但是让浏览器执行热刷新的最后一步没有按预期工作。我将尝试在此处发布所有相关设置。如果您需要其他任何东西来找出我在哪里做错了,请告诉我:

我使用 node ./server/index.js 启动我的应用程序

webpack.config.js var path = require('路径'); 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.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

当我对包含矩形组件的 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 Application = () => {
  return (
    <div id="maincontent">
      <MainMenu />
      <ScreenContents />          
    </div>
  )
};

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

我必须像这样显式地创建我的类:

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/
}

关于node.js - 让 webpack 热更新在我的同构网络应用程序中正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35301836/

相关文章:

javascript - WebRTC 重新协商对等连接以切换流

css - 我可以使用 Express.js 动态渲染 css 吗?

javascript - 错误 : Uncaught ReferenceError: React is not defined

node.js - 在 Express 中将变量传递到路由模板的最简单方法?

JavaScript 日期格式忽略时区

node.js - 无法使用 Windows 10 安装 firebase 工具 cli

node.js - Mongo 使用 req.query.id Node 查找 id

javascript - 如何使用 expressjs 写入 HTML 文件

webpack - Vue 2 + VueRouter 2 + Laravel 5.3 - Webpack(运行时 x 独立构建问题)

javascript - webpack 找不到 bundle.js