【问题标题】:webpack hot module replacement not workingwebpack热模块更换不起作用
【发布时间】:2020-02-06 23:33:05
【问题描述】:

我试图在我的 webpack 配置中使用 HRM(热模块替换),首先我在 package.jsong 中设置了 --hot 选项:

"scripts": {
    "start": "webpack-dev-server --hot"
}

还请注意,我使用 HtmlWebpackPlugin 为我创建一个 index.html 文件并将其放在“build”目录中,这是我的完整 webpack.config.js 文件:

const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserJSPlugin = require('terser-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const WebpackManifestPlugin = require('webpack-manifest-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
// const webpack = require('webpack');
const mode = "development";

module.exports = {
  mode: mode,
  // watch: true,
  devtool: "cheap-module-eval-source-map",
  devServer: {
    port: 9000,
    // contentBase: path.resolve(__dirname, 'build')
  },
  entry: {
    application: "./src/javascripts/index.js",
    admin: "./src/javascripts/admin.js"
  },
  output: {
    filename: mode === 'production' ? "[name]-[contenthash].js" : '[name].[hash].js',
    path: path.resolve(__dirname, 'build'),
    // publicPath: '/'
  },
  optimization: {
    minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
  },
  plugins: [
    new MiniCssExtractPlugin({
        filename: mode === 'production' ? "[name]-[contenthash].css" : "[name]-[hash].css",
        hmr: mode === 'production' ? false : true
    }),
    new CleanWebpackPlugin(),
    new WebpackManifestPlugin(),
    new HtmlWebpackPlugin({
      template: './src/template.html',
      // filename: '../index.html'
    })
    // new webpack.HotModuleReplacementPlugin()
  ],
  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      },
      {
        test: /\.css$/i,
        use: [
          MiniCssExtractPlugin.loader,
          { loader: 'css-loader', options: { importLoaders: 1 } },
          {
            loader: 'postcss-loader',
            options: {
              plugins: [
                require('autoprefixer')({
                  overrideBrowserslist: ['last 3 versions', 'ie > 9']
                })
              ]
            }
          },
        ],
      },
      {
        test: /\.scss$/i,
        use: [
          MiniCssExtractPlugin.loader,
          { loader: 'css-loader', options: { importLoaders: 1 } },
          {
            loader: 'postcss-loader',
            options: {
              plugins: [
                require('autoprefixer')({
                  overrideBrowserslist: ['last 3 versions', 'ie > 9']
                })
              ]
            }
          },
          'sass-loader'
        ],
      },
      {
        test: /\.(png|jpg|gif|svg)$/i,
        use: [
          {
            loader: 'file-loader',
            options: {
              limit: 8192,
              name: '[name].[hash:7].[ext]'
            },
          },
          {
            loader: 'image-webpack-loader'
          }
        ],
      }
    ]
  }

}

如您所见,我主要使用的条目是./src/javascripts/index.js,我在其中导入了一个名为 application.scss 的文件:

import application from "../stylesheets/application.scss"

application.scss 包含:

span{
  background-color: blue;
}

因此,每当我更改位于我的 html 页面中的 span 的背景颜色时,我都想热重新加载页面。

当我运行 npm run start 时,我会更改 span 的背景颜色,更新会第一次起作用(但它会重新加载整页)然后如果我尝试再次更改背景颜色什么都没有更新,我在控制台中看到的只是:

[HMR] Nothing hot updated. log.js:24
[HMR] App is up to date.

我不确定这里缺少什么,但有人可以看到做错了什么?

【问题讨论】:

    标签: javascript webpack webpack-dev-server hot-reload


    【解决方案1】:

    从文档中,

    它会在尝试重新加载整个页面之前尝试使用 HMR 进行更新

    所以,大概,如果失败了,它只会重新加载整个页面,这就是你所看到的。

    您是否尝试在主条目文件的末尾包含此内容?

    if (module.hot) {
      module.hot.accept(function (err) {
        console.log('An error occurred while accepting new version');
      });
    }
    

    另外,检查 Chrome 开发者工具的 network 标签的 -hot.js 文件请求 --- 它们的状态是 200、404、500 吗?也许您的服务器正在崩溃或无法正确提供服务。

    确保在你的 webpack 中你也有

    devServer: {
      // contentBase: './dist', // this watches for html changes, apparently?
      contentBase: path.resolve(__dirname, 'build') // in your specific case maybe?
      hot: true,
    },
    

    【讨论】:

    • 我包含了你建议的代码,但没有出现错误,而且 -hot.js 文件在我的控制台中都是 200 个,当我看到我的终端时它仍然说“没有热更新”注意到Entrypoint undefined = index.html这里是截图:i.imgur.com/zybOtvZ.png
    • 这似乎是 htmlWebpackPugin 的问题我找到了这个解决方案 github.com/cxphoe/html-webpack-hot-plugin 但它对我不起作用
    • 我不确定我明白了你的意思,但是改变的是css文件,HMR应该反映这个改变到html页面,如果我改变颜色,颜色应该在页面,就这么简单!
    • 尝试 contentBase 到你的构建目录?
    猜你喜欢
    • 2015-05-31
    • 2016-12-23
    • 2016-04-30
    • 2017-06-28
    • 2018-09-22
    • 1970-01-01
    • 2017-02-27
    • 2016-04-05
    • 2020-06-29
    相关资源
    最近更新 更多