preface

Before WebPack 4.0, we used the extract-text-webpack-plugin to extract CSS styles from JS files into separate CSS files. The extract-text-webpack-plugin has advantages and disadvantages:

For more information, please see:
Webpack.docschina.org/plugins/ext…

After WebPack 4.0, it is officially recommended to use the mini-CSS-extract-plugin to package CSS files (extract CSS code from CSS files into separate files, compress CSS code, etc.).

Method of use

Place all configuration files in the root directory of your project and run the command in package.json. Of course, the basic configuration of the entrance and exit of Webpack needs to be completed by referring to the official website documents.

This document uses three configuration files to explain their configurations and precautions.

Webpack.common.js (common configuration file)

  • Configuration shared by development and production environments, with the help ofwebpack-mergePlug-ins that can be merged into development or production environments to reduce duplication of configuration.
  • Node environment variables were introducedprocess.env.NODE_ENVThe configuration can be changed dynamically based on the environment parameters passed in, as shown in the code.
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
constdevMode = process.env.NODE_ENV ! = ='production'

module.exports = {
  module: {
    rules: [{test: /\.(sa|sc|c)ss$/.// You can package files with suffixes sass/ SCSS/CSS
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              // You can specify a publicPath here
              // publicPath in webPackoptions. output is used by default
              // publicPath is configured according to the filename and chunkFilename names specified in plugins
              // If the image in the background attribute cannot be displayed after packaging, check whether the publicPath configuration is correct
              publicPath: '/'.// publicPath: devMode ? '/', '.. /', // Specify a different publicPath for different environments
              hmr: devMode, // The HMR function is enabled only in the dev environment}},'css-loader'.'sass-loader'],},]},plugins: [
    new MiniCssExtractPlugin({
      // The configuration here is similar to webpackOptions.output
      // You can add the path before the name to determine the path of the packaged file
      filename: devMode ? 'css/[name].css' : 'css/[name].[hash].css'.chunkFilename: devMode ? 'css/[id].css' : 'css/[id].[hash].css',}})]Copy the code

Webpack.dev.js (configuration file for dev environment)

  • Dev environment configuration, remembermodeSet todevelopmentMode, otherwise WebPack4 defaults toproductionMode.
const merge = require('webpack-merge')
const common = require('./webpack.common')
const webpack = require('webpack')

module.exports = merge(common, {
  mode: 'development'
})

Copy the code

Webpack.prod.js (configuration file for production environment)

  • For production configuration, tree-shaking and JS code compression are enabled by default;
  • throughoptimize-css-assets-webpack-pluginPlug-ins can compress CSS, and at the same time, you must specify the JS compression plug-in (used in the example)terser-webpack-pluginPlugins), otherwise WebPack no longer compresses JS files;
  • Set up theoptimization.splitChunks.cacheGroups, you can extract blocks of CSS code into separate files.
const path = require('path')
const merge = require('webpack-merge')
const common = require('./webpack.common')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const TerserJSPlugin = require('terser-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');

module.exports = merge(common, {
  mode: 'production'.optimization: {
    minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
    splitChunks: {
      cacheGroups: {
        styles: {
          name: 'styles'.test: /\.css$/.chunks: 'all'.enforce: true,},}},}})Copy the code

Package. json configuration file

  • SideEffects:Tree-shaking is enabled by default when the production environment is packaged, if not setsideEffectsSome pass throughimportCSS files that are brought in May not be packaged, because tree-shaking shakes off files that export nothing (that is, files without the export keyword).So, if you don’t want to be shaken by tree-shaking, please visitsideEffectsTo configure the regular expression that matches it (added below in package.json).
  • NODE_ENV:Since Node environment variables are used in the project, the package must be passedNODE_ENVPass in environment variables. This configuration is no problem in macOS operation, Windows buddy, you can install a calledcross-envNPM package, use method (installationnpm i cross-env -S, add “cross-env” before the command, for example: “scriipt”:{“dev”: “cross-env NODE_ENV=development webpack –config webpack.dev.js –progress”}).
{ "sideEffects": [ "*.css", "*.scss", "*.sass" ], "scripts": { "build": NODE_ENV=production webpack --config webpack.prod.js --progress", NODE_ENV=development webpack --config webpack.dev.js --progress", // dev environment package},}Copy the code

conclusion

  • If the image cannot be displayed (especially in THE CSS), please check the packaging in different environmentspublicPathThe configuration.
  • mode: 'production'Tree -shaking and JS compression are enabled, but configuredoptimization. minimizerThe default compression function is disabled. Therefore, when specifying the CSS compression plug-in, you must specify the JS compression plug-in.
  • mini-css-extract-pluginPlug-ins, combinedoptimization.splitChunks.cacheGroupsConfiguration, you can package CSS code into a separate CSS file, and you can set the storage path (by setting the plugin’sfilenameandchunkFilename).

The official document: webpack.js.org/plugins/min…

If there are any mistakes, feel free to correct them in the comments section!