Webpack开发服务器(webpack-dev-server)热模块替换(HMR)无法正常工作

12

我在StackOverflow和GitHub的问题中找到了许多答案,但是我仍然无法解决Webpack中的热模块替换问题。我使用npm start以及webpack-dev-server--hot--inline来运行服务器。我想改变React组件中的代码,但是浏览器中没有任何变化。

我的浏览器是Google Chrome Version 49.0.2623.87(64位)在Ubuntu 14.04LTS上。

在我的浏览器控制台中,我得到以下日志消息:

[HMR] Waiting for update signal from WDS...

[WDS] Hot Module Replacement enabled.

但是,没有热/实时重新加载发生。当我改变React组件文件中的代码时,没有显示任何内容。我正在遵循这个教程的第一个视频,Egghead.io/ReactFundamentals,在那里一切都正常。

以下是我的package.json和webpack.config.js文件。

package.json

{
  "name": "react-fundamentals",
  "version": "1.0.0",
  "description": "Fundamentals of ReactJS",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --hot --inline"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^15.0.0-rc.2",
    "react-dom": "^15.0.0-rc.2"
  },
  "devDependencies": {
    "babel": "^6.5.2",
    "babel-core": "^6.7.2",
    "babel-loader": "^6.2.4",
    "babel-preset-es2015": "^6.6.0",
    "babel-preset-react": "^6.5.0",
    "react-hot-loader": "^1.3.0",
    "webpack": "^1.12.14",
    "webpack-dev-server": "^1.14.1"
  }
}

webpack.config.js

module.exports = {
  context: __dirname,
  entry: "./main.js",
  output: {
    path: __dirname,
    filename: "bundle.js"
  },
  devServer: {
    port: 7777
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: "babel",
        query: {
          presets: ["es2015", "react"]
        }
      }
    ]
  }
}

如果有人能够指导我解决这个问题,那就太好了,因为我无法有效地跟进教程。

更新 我已经在下面发布了答案。


你是否收到任何错误信息?你仍然在使用7777端口访问应用程序吗? - markthethomas
它是一个无状态的函数组件吗?你的应用程序是否在像 Vagrant 这样的虚拟机上运行? - azium
@markthethomas 不,我没有收到任何错误。Bundle 已经验证,并显示消息“webpack: bundle is now VALID.”。是的,我正在端口7777上访问该应用程序。 - krishnaxv
@azium 不,我没有使用任何像Vagrant这样的虚拟机。 - krishnaxv
@azium 不,它不是一个无状态函数组件。 - krishnaxv
显示剩余2条评论
6个回答

5

我自己找到了解决方案。

我必须使用sudo来运行我的服务器。不是用npm start,而是要使用sudo npm start

希望对你有所帮助!


1
即使我在npm startnpm run start前面使用sudo,我仍然无法使其工作,但我确信在运行其中一个命令时,带或不带sudowebpack-dev-server已经在运行。 - Casper
1
它对我起作用了。感谢您的解决方案...但我仍然好奇它是如何工作的。 - Karan

3
devServer: {
 inline: true, // you missed this line which will reload the browser
 port : 7777
}

我之前已经按照提到的教程尝试过了,但是没有成功。后来我将它改成了 webpack-dev-server --hot --inline - krishnaxv

3
你的webpack配置有误。请查看react-transform-boilerplate以获取正确的设置。

webpack.config.js

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

module.exports = {
  // or devtool: 'eval' to debug issues with compiled output:
  devtool: 'cheap-module-eval-source-map',
  entry: [
    // necessary for hot reloading with IE:
    'eventsource-polyfill',
    // listen to code updates emitted by hot middleware:
    'webpack-hot-middleware/client',
    // your code:
    './src/index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/dist/'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  module: {
    loaders: [{
      test: /\.js$/,
      loaders: ['babel'],
      include: path.join(__dirname, 'src')
    }]
  }
};

.babelrc

{
  "presets": ["react", "es2015"],
  "env": {
    "development": {
      "presets": ["react-hmre"]
    }
  }
}

我不喜欢react-transform-boilerplate,因为它现在还处于实验阶段。此外,我想要使用webpack-dev-server自身进行热/实时重载,而不涉及react-hot-loader插件,因为我现在想保持简单。你在我的配置文件中发现了任何特定的错误吗?谢谢回复! - krishnaxv
一旦我能够弄清楚这个问题,我一定会尝试使用react-transform-boilerplate - krishnaxv

1

我刚刚删除了node_modules文件夹和package-lock.json文件。然后重新运行npm install。它起作用了!


0
我使用以下版本: "webpack": "~1.12.14" "webpack-hot-middleware": "^2.10.0" "webpack-dev-middleware": "^1.6.1"
在我的 React.js 项目中的 app.js 文件中,我使用以下代码。
    var webpackconfig =require('./webpack.config');
    var webpack = require('webpack');
    var webpackMiddleware = require('webpack-dev-middleware');
    var webpackHotMiddleware = require('webpack-hot-middleware');

    var http = require('http');
    var express = require('express');
    var app = require('express')();
    var isDeveloping = process.env.NODE_ENV != 'production';
    // var isDeveloping = false;
     console.log("IS developing ",isDeveloping);
   var serverConfig = require('./globalconfig.js')

   var serverPort = serverConfig.port

   app.get('/css/bootstrap.min.css', function (req, res) {
   res.sendFile(path.join(__dirname,           'public/lib/bootstrap/css/bootstrap.min.css'));
   });



     // swaggerRouter configuration
     var options = {
     controllers: './controllers',
     useStubs: process.env.NODE_ENV === 'development' ? true : false    // Conditionally turn on stubs (mock mode)
     }

     var config = {
      appRoot: __dirname // required config
      }


     // Start the server
     app.listen(serverPort, function () {
       console.log('Your server is listening * on port %d        (http://localhost:%d)', serverPort, serverPort);
});


     if (isDeveloping) {
        app.use('/node_modules', express.static('/node_modules'));
        app.use(express.static('src/web-ui/public/'));
        app.use(express.static('src/web-ui/public/'));
        const compiler = webpack(webpackconfig);
        const middleware = webpackMiddleware(compiler,{
         publicPath: webpackconfig.output.publicPath,
        headers: {
          "Cache-Control" : "public, max-age=604800"
        },
       constentBase:'dist',
       stats:{
         color:true,
         hash:false,
         timings:true,
          chunks:false,
         chunkModules:false,
         modules:false
       }

      });
      app.use(middleware);
      app.use(webpackHotMiddleware(compiler));
      app.get('/',function response(req,res){
                         res.write(middleware.fileSystem.readFileSync(path.join(_dirname,'dist/index.html')));
       res.end();
       });
    } else {
       app.use('/node_modules', express.static('/node_modules'));
       app.use(express.static('dist/public'));
       app.use(express.static('dist'));

       app.get('/', function response(req, res,next) {
         console.log("Processing req");
         var entryFile = path.join(__dirname, 'dist', 'index.html');
          console.log("Hitting the Root",entryFile);
          res.sendFile(entryFile);
        });
       }

相同的代码可以热替换到其他员工的电脑上,但并不总是可行的。在我的电脑上很多时候热替换无法正常工作。


-2

尝试更新您的模块加载器为以下内容:

loaders: [
      {
        test: /\.jsx$/,
        exclude: /node_modules/,
        loaders: ["react-hot", "babel"],
        query: {
          presets: ["es2015", "react"]
        }
      }
    ]

react-hot-loader已经被弃用。 - Brigand
他在依赖项列表中列出了它。 - Nico Galluzzo

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