Webpack系列(七):css文件的代码分割

怎么对css文件进行代码分割?

如果我们想让引入的css文件,在打包时,单独生成一个css文件到dist目录的话,可以这样做

  • 先下载一个插件

    npm install --save-dev mini-css-extract-plugin
    
  • 在webpack.config.js中进行配置

    const MiniCssExtractPlugin = require('mini-css-extract-plugin');
    
    module.exports = {
      plugins: [new MiniCssExtractPlugin()],
      module: {
        rules: [
          {
            test: /\.css$/i,
            use: [MiniCssExtractPlugin.loader, 'css-loader'],
          },
        ],
      },
    };
    
  • 这时候你会发现,引入的css文件,不会生成到js中,而是单独生成了css文件

如果想要对打包的css进行压缩怎么处理呢?

  • 下载插件
npm install optimize-css-assets-webpack-plugin -D
  • 在webpack.config.js中进行配置
const TerserJSPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');

module.exports = {
  optimization: {
    minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].css',
      chunkFilename: '[id].css',
    }),
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
      },
    ],
  },
};

如何将所有CSS提取到一个文件中呢?

在webpack.config.js中进行配置可以忽略上面两个配置,但是插件一定要下载

const TerserJSPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');

module.exports = {
  optimization: {
    splitChunks: {
      cacheGroups: {
        styles: {
          name: 'styles',
          test: /\.css$/,
          chunks: 'all',
          enforce: true,
        },
      },
    },
    minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].css',
      chunkFilename: '[id].css',
    }),
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
      },
    ],
  },
};

具体高级用法可以参考webpack官网:https://webpack.js.org/plugins/mini-css-extract-plugin/

你可能感兴趣的:(webpack)