React + webpack 热更新后修改了样式文件,但是不能及时生效的解决办法

使用了webpack的热更新后,修改样式文件,不能热更新到样式文件上,只能打包到服务器上,样式文件才会生效。
具体的原因是因为我将样式文件和js文件分开了,所以样式文件不会生效。
解决办法就是在开发环境中将样式文件和js文件合并,正式环境中再 将其分开。

先看webpack.config.js

const plugins = require('./plugin');
const jsRules = require('./rules/jsRules');
const styleRules = require('./rules/styleRules');
const fileRules = require('./rules/fileRules');
const optimization = require('./optimization');
// 映射 tsconfig 路径
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const { resolve } = require('./utils');

module.exports = (env, argv) => ({
    entry: {
        sysmanage: resolve('src/modules/system/app.tsx'),
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.jsx'],
        plugins: [
            new TsconfigPathsPlugin({
                configFile: resolve('tsconfig.json')
            })
        ]
    },
    output: {
        path: resolve('dist'),
        publicPath: '/static/',
        filename: 'js/[name].js'
    },
    module: {
        rules: [...styleRules.config(argv.mode), ...fileRules, ...jsRules],
    },
    plugins: [...plugins],
    optimization,
    devServer: {
        port: 8080,
        proxy: {
            '/': {
                target: 'http://localhost:8083/',
                secure: false
            }
        }
    },
});

再看styleRule.js

// css分离
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const theme = require('../../__config__/theme');
const { resolve } = require('./../utils');
let config = (mode) => {
  return [
    {
      test: /\.css$/,
      use: [
        mode === 'development' ? 'style-loader' : MiniCssExtractPlugin.loader,
        {
          loader: 'css-loader',
          options: { importLoaders: 1 }
        },
        'postcss-loader'
      ]
    },
    {
      test: /\.less$/,
      use: [
        mode === 'development' ? 'style-loader' : MiniCssExtractPlugin.loader,
        'css-loader',
        {
          loader: 'cache-loader',
          options: {
            cacheDirectory: resolve('.cache-loader')
          }
        },
        {
          loader: 'postcss-loader',
          options: {
            sourceMap: true
          }
        }, {
          loader: 'less-loader',
          options: {
            javascriptEnabled: true,
            modifyVars: theme,
            importLoaders: 1
          }
        }
      ]
    }
  ];
}
module.exports = {
  config
}

这里我将css分离、文件规则等配置分离到其他js中,这里就写了样式文件。

你可能感兴趣的:(React + webpack 热更新后修改了样式文件,但是不能及时生效的解决办法)