Webpack开发中间件React热重载速度太慢

14

我使用webpack-dev-middlewarewebpack-hot-middleware简单地配置了一个能够与React使用热更新(HMR)的项目。

一切都正常运行,但是每次代码更改后,在浏览器中看到更改需要2-3秒甚至更长时间!我做错了什么吗?难道这就是正常的表现?

我的代码相当大,打包后最小化后达到841kb(经过gzip压缩只有200kb),这是原因吗?代码库越大,打包就会越慢吗?

Express服务器:

var webpack = require('webpack');
var webpackConfig = require('./webpack.hot.config');
var compiler = webpack(webpackConfig);

app.use(require("webpack-dev-middleware")(compiler, {
  noInfo: true,
  publicPath: webpackConfig.output.publicPath,
  watchOptions: {
    poll: true
  }
 }));
app.use(require("webpack-hot-middleware")(compiler, {
  log: console.log,
  path: '/__webpack_hmr',
  heartbeat: 10 * 1000
 }));

webpack.hot.config.js

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

module.exports = {

context: __dirname,
entry: [
    'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000',
    './src/js/index'
],
module: {
    loaders: [{
        test: /\.jsx?$/,
        include: path.join(__dirname, 'src/js'),
        //exclude: /node_modules/,
        loader: 'react-hot!babel'
    },
        {
            // Test expects a RegExp! Note the slashes!
            test: /\.css$/,
            loaders: ['style', 'css'],
            // Include accepts either a path or an array of paths.
            include: path.join(__dirname, 'src/css')
        }
    ]
},
resolve: {
    extensions: ['', '.js', '.jsx']
},
output: {
    path: __dirname + '/public',
    publicPath: '/',
    filename: 'js/app.js'
},
plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
]
};

我在代码中做出更改后,在控制台上看到了以下内容:

[HMR] App is up to date.
app.js:73223 [HMR] bundle rebuilding
app.js:73226 [HMR] bundle rebuilt in 335ms
app.js:73289 [HMR] Checking for updates on the server...
app.js:73362 [HMR] Updated modules:
app.js:73364 [HMR]  - ./src/js/components/header.jsx
app.js:73369 [HMR] App is up to date.

因此,“exclude:/ node_modules /”被注释掉了。当它在配置中时,构建是否仍然很慢?除此之外,我建议删除OccurrenceOrderPlugin。该插件旨在帮助分块,而您似乎没有实施它(除非您在不同的配置文件中)。 - garrettmaring
@garrettmaring,使用include代替exclude应该足够了,因为它是更明确的变体。过去,我认为我还需要使用OccurenceOrderPlugin来确保webpack-dev-middleware的热重载。 - John William Domingo
3个回答

6

专业提示:webpack.config.js中更改模式为开发模式。如果您不设置该属性,默认情况下它将使用生产模式,意味着它会执行缓慢的生产操作,并使热重载变得困难。

module.exports = {
    mode: 'development'
};

5

考虑将中间件的轮询(polling)设置为 false。我发现轮询会占用大量 CPU 资源。

在你的 webpack 配置中,你可能还想尝试添加 devtool: false 来避免生成源映射。


1
似乎那并没有帮助。 - Adidi
1
在Windows上使用Docker时,这并不是一个选项。 - wintercounter

1
你应该启用缓存:
    ...
    plugins: [
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoErrorsPlugin()
    ],
    cache: true
};

1
似乎那并没有帮助。 - Adidi
@Adidi,你找到解决方案了吗?否则,你可以查看https://webpack.js.org/plugins/dll-plugin/。 - hampusohlsson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接