简体   繁体   English

webpack 热模块更换不工作

[英]webpack hot module replacement not working

Am trying to use HRM (Hot Module Replacement) in my webpack config, first I have set the --hot option within my package.jsong:我试图在我的 webpack 配置中使用 HRM(热模块更换),首先我在 package.jsong 中设置了 --hot 选项:

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

Also note that am using the HtmlWebpackPlugin in order to create an index.html file for me and put it in a "build" directory, here is my full webpack.config.js file:另请注意,我正在使用 HtmlWebpackPlugin 为我创建一个 index.html 文件并将其放在“构建”目录中,这是我的完整 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'
          }
        ],
      }
    ]
  }

}

As you see the entry I use mainly is ./src/javascripts/index.js where am importing a file called application.scss:如您所见,我主要使用的条目是./src/javascripts/index.js ,其中导入了一个名为 application.scss 的文件:

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

the application.scss contains: application.scss 包含:

span{
  background-color: blue;
}

So I want to hot reload the page whenever I change the background color of the span located in my html page.因此,每当我更改位于我的 html 页面中的跨度的背景颜色时,我都想重新加载页面。

when I run npm run start then I change the background color of the span the update works the first time ( BUT IT DOES A FULL PAGE RELOAD ) then if I try to change the background color again nothing get updated and all I see in the console is this:当我运行npm run start然后我更改跨度的背景颜色,更新第一次工作(但它确实是一个完整的页面重新加载)然后如果我尝试再次更改背景颜色,没有任何更新,我在控制台中看到的所有内容这是:

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

Am not sure what am missing here, but someone can see what am doing wrong?不确定这里缺少什么,但有人可以看到做错了什么?

From the documentation,从文档中,

it tries to update with HMR before trying to reload the whole page在尝试重新加载整个页面之前,它会尝试使用 HMR 进行更新

So, presumably, if that fails, it will just reload the entire page, which is what you're seeing.因此,据推测,如果失败,它将重新加载整个页面,这就是您所看到的。

Have you tried including this at the end of your primary entry file?您是否尝试在主条目文件的末尾包含此内容?

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

Also, inspect the -hot.js file requests of network tab of Chrome's developer tools --- are they status 200, 404, 500?此外,检查 Chrome 开发者工具的network选项卡的-hot.js文件请求 --- 它们的状态是 200、404、500 吗? Maybe your server is crashing or not serving them correctly.也许您的服务器正在崩溃或无法正确提供服务。

Ensure in your webpack that you also have确保在您的 webpack 中您也有

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM