webpack-dev-server在HTML或Sass更改时无法重新加载

11

我的项目有这种结构:

\root    
   \webpack.config.js
   \public
     \ index.html
     \ ...
     \ css
     \ directives
     \ views   
     \ dist (webpack output)
       \app.js
       \ index.html
       \ app.js.map   
       \ style.css
       \ style.css.map

当我使用webpack-dev-server时,我从/root目录启动它并加载应用程序。但是,当我更改sass文件或html文件时它不会重新加载。webpack配置有什么问题?

启动webpack的命令:

$ cd root
$ webpack-dev-server

Webpack配置文件

const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');

const webConfig = {
  entry: path.join(__dirname, 'public', 'js', 'app'),
  output: {
    path: path.join(__dirname, 'public', 'dist'),
    filename: 'app.js'
  },
  resolve: {
    modules: [__dirname, 'node_modules'],
    extensions: ['.js'],
    enforceExtension: false,
  },
  devtool: 'source-map',
  devServer:{
    contentBase: 'public/',
    publicPath: 'public/'
  },
  module: {
    loaders: [
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract({
          loader: 'css-loader?modules,localIdentName=[name]__[local]--[hash:base64:5]!sass-loader'
        }),
        exclude: /node_modules/
      },
      {
        test: /\.html$/,
        loader: "raw-loader" // loaders: ['raw-loader'] is also perfectly acceptable.
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin({filename: 'style.css', allChunks: true}),
    new HtmlWebpackPlugin({
      template: './public/index.html'
    })
  ]
};

module.exports = webConfig;
4个回答

8

https://medium.com/@rajaraodv/webpack-the-confusing-parts-58712f8fcad9

“inline”选项为整个页面添加了“实时重新加载”的功能。 “hot”选项启用了“热模块重载”,尝试重新加载仅更改的组件(而不是整个页面)。 如果我们传递两个选项,那么当源代码更改时,webpack-dev-server将首先尝试HMR。 如果这不起作用,则重新加载整个页面。

尝试将此添加到您的webpack.config文件中:

devServer:{
    contentBase: 'public/',
    publicPath: 'public/',
    inline: true,
    hot: true,
  },

如果需要的话,您也可以从package.json文件中调用脚本。像这样的一些东西:
...
scripts: {
   "watch": "webpack-dev-server --progress --colors --hot --inline",
}
...

截至2018年1月18日,我的Webpack热重载突然停止工作了。我不得不在webpack.config中手动添加inline和hot到我的devServer配置!非常感谢这个答案! - Gavin Thomas

7

这对我来说在webpack 5.68.0上有效。 - user3533413

1
在你的devServer配置中添加选项watchContentBase: true。
停止当前活动并重新加载脚本。

devServer: {
        contentBase: path.join(__dirname, 'public'),
        port: 9000,
        open:true,
        liveReload: true,
        watchContentBase: true,
      },


0
如果你使用HtmlWebpackPlugin,请尝试将其移除,weback-dev-server/webpack serve可以自动选择./public下的html文件。

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