Webpack 4 Hot Module Replacement仅适用于样式表

时间:2019-03-21 23:08:40

标签: webpack

我开始学习Webpack4,并且无法管理HMR正常工作。 我有以下结构:

>dist
  index.html
  bundle.js
>src
  >img
  >css
    style.scss
  >modules
    someModule.js
  index.html
  index.js

在package.json中,我有:

"script": {
    "devStart": "webpack-dev-server --mode development --open"
},
"devDependencies": {
    "@babel/core": "^7.4.0",
    "@babel/preset-env": "^7.4.2",
    "babel-loader": "^8.0.5",
    "css-loader": "^2.1.1",
    "file-loader": "^3.0.1",
    "html-loader": "^0.5.5",
    "html-webpack-plugin": "^3.2.0",
    "mini-css-extract-plugin": "^0.5.0",
    "node-sass": "^4.11.0",
    "sass-loader": "^7.1.0",
    "style-loader": "^0.23.1",
    "webpack": "^4.29.4",
    "webpack-cli": "^3.2.3",
    "webpack-dev-server": "^3.2.1"
  }

在webpack.config.js中:

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
        path: path.join(__dirname, 'dist')
    },
    devServer: {
        contentBase: path.join(__dirname, 'src'),
        port: 8888,
        inline: true,
        hot: true
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env']
                    }
                }
            },
            {
                test: /\.html$/,
                use: {
                    loader: 'html-loader',
                    options: {
                        minimize: true
                    }
                }
            },
            {
                test: /\.scss$/,
                use: [
                    { loader: 'style-loader' },
                    { loader: 'css-loader' },
                    { loader: 'sass-loader' }
                ]
            },
            {
                test: /\.(png|svg|jpg|jpeg|gif)$/,
                use: {
                    loader: 'file-loader'
                }
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html'
        }),
        new MiniCssExtractPlugin({
            filename: "[name].css",
            chunkFilename: "[id].css"
        }),
        new webpack.HotModuleReplacementPlugin()
    ]
};

我在index.js中导入样式,并且只有该文件中的更改才会调用HMR。 当我更改index.html时,我必须手动重新加载,并且当我更改引起完全重新加载的module或index.js文件时。

当我将hotOnly设置为true时,我得到了错误:

Ignored an update to unaccepted module ./src/index.js
[HMR] The following modules couldn't be hot updated: (They would need a full reload!)

0 个答案:

没有答案