首页 > 解决方案 > 在 React 中使用 Webpack 创建缩小的 CSS 文件

问题描述

这是我第一次在 React 项目中配置 webpack。我已将 Sass 和 glob 加载器配置为从我的组件文件夹中动态导入所有 SCSS 文件。问题是所有样式都附加在头部的全局样式标签中。如何为我的项目创建一个缩小的 CSS 文件。我尝试使用 MiniCSSExtract 插件,但我不知道它是否用于创建项目样式的缩小文件。我在下面发布了我的 webpack.config.js 文件。

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

var HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
  template: __dirname + '/public/index.html',
  filename: 'index.html',
  inject: 'body'
});


module.exports = {
   entry: ['./src/main.js', './src/main.scss'],
   output: {
      path: path.join(__dirname, '/dist'),
      filename: 'bundle.js',
      publicPath: '/'
   },
   devServer: {
      inline: false,
      contentBase: "./dist",
      port: 8001
   },
   module: {
      rules: [
         {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
         },
         {
          test: /\.js$/,
          use: 'webpack-import-glob-loader'
        },
        {
          test: /\.scss$/,
          use: ['style-loader', 'css-loader', 'sass-loader', 'webpack-import-glob-loader']
        },
        { 
          test: /\.json$/, 
          loader: 'json' 
        },
        {
          test: /\.css$/i,
          use: [MiniCssExtractPlugin.loader, 'style-loader', 'css-loader'],
        }
      ]
   },
   devServer: {
    historyApiFallback: true
  },
   plugins:[
    new MiniCssExtractPlugin(),
    HtmlWebpackPluginConfig
   ]
}

这是我的 index.html,我在其中添加了由 webpack 创建的 bundle.js。

<!DOCTYPE html>
<html lang = "en">
   <head>
      <meta charset = "UTF-8">
      <title>React App</title>
   </head>
   <body>
      <div id="app"></div>
      <script src='bundle.js'></script>
   </body>
</html>

标签: javascriptcssreactjswebpack

解决方案


所以在仔细检查和阅读 Webpack 插件的文档后,我能够解决这个问题,我也了解了 webpack 提供的缓存破坏器。如果有人在不久的将来寻找配置,可能对他们有用。

const currentTask = process.env.npm_lifecycle_event;
const path = require('path')
const MiniCSSExtractPlugin = require('mini-css-extract-plugin')
const HTMLWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const { WebpackManifestPlugin } = require('webpack-manifest-plugin')

const config = {
  entry: './app/app.js',
  output: {
    filename: 'myBundle.[hash].js',
    path: path.resolve(__dirname, 'dist')
  },
  plugins: [new HTMLWebpackPlugin({ template: './app/index.html', inject: 'body' })],
  mode: "development",
  devServer: {
    port: 8080,
    contentBase: path.resolve(__dirname, 'dist'),
    hot: true
  },
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: ["style-loader", "css-loader", "sass-loader"]
      },
      {
        test: /\.js$/,
        exclude: /(node_modules)/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ['@babel/preset-env', '@babel/preset-react']
          }
        }
      }
    ]
  }
}

if(currentTask == "build") {
  config.mode == "production";
  config.module.rules[0].use[0] = MiniCSSExtractPlugin.loader
  config.plugins.push(new MiniCSSExtractPlugin({filename: 'main.[hash].css'}), new CleanWebpackPlugin(), new WebpackManifestPlugin())
}

module.exports = config;

推荐阅读