Steps to split and compress CSS with webpack and import it with link

Steps to split and compress CSS with webpack and import it with link

Let's take a look at the code file structure first:

Contents of the entry file (index1.js):

import $ from 'jquery'
import './css/index.css'
import './less/index.less'
$(function () {
    $('#app li:nth-child(odd)').css('color', 'red')
    $('#app li:nth-child(even)').css('color', 'green')
})
 
import './assets/fonts/iconfont.css';
const ul = document.querySelector("ul");
const theI = document.createElement("li");
theI.className='iconfont icon-qq';
ul.appendChild(theI);

Contents of the webpack.config.js configuration file:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    //Entry file address entry: './src/index1.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        //Export file name filename: 'bundle.js',
    },
    plugins: [
        new HtmlWebpackPlugin({
        template: './public/interlaced color.html'
    })],
     module: {
         rules: [{
             //Match files ending with .css, i is case insensitivetest: [/\.css$/i],
            //Execute from right to left, the order cannot be changed. Style-loader inserts CSS into DOM, and css-loader processes @import and url(), just like js parses import/require(). use: ["style-loader", "css-loader"],
         }, {
             test: /\.less$/i,
                 use: [
                     // compiles Less to CSS
                     'style-loader',
                     'css-loader',
                     'less-loader',
                 ],
             }, { // webpack5 does not recognize these files by default, so just output them as static resources test: /\.(eot|svg|ttf|woff|woff2)$/,
                 type: 'asset/resource',
                 generator: {
                     filename: 'font/[name].[hash:6][ext]'
                 }
             }],
     },
};

We package and then run the packaged html file:

It is found that the css style is added in the form of style tags generated by js

After running the package, we will find that less is converted to a css file, but the css file is added with a style tag through js. Next, we will split the css out and introduce it with a link tag

step:

1. Install mini-css-extract-plugin

npm i mini-css-extract-plugin -D //npm installation yarn add mini-css-extract-plugin -D //yarn installation

2. Introduce and configure in webpack.config.js file

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
//Introduce the installed mini-css-extract-plugin
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
    //Entry file address entry: './src/index1.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        //Export file name filename: 'bundle.js',
    },
    plugins: [new MiniCssExtractPlugin(),
        new HtmlWebpackPlugin({
        template: './public/interlaced color.html'
    })],
     module: {
         rules: [{
             //Match files ending with .css, i is case insensitivetest: [/\.css$/i],
            //Execute from right to left, the order cannot be changed. Style-loader inserts CSS into DOM, and css-loader processes @import and url(), just like js parses import/require(). use: [MiniCssExtractPlugin.loader, "css-loader"
             ],
         }, {
             test: /\.less$/i,
                 use: [
                     // compiles Less to CSS
                     MiniCssExtractPlugin.loader,
                     'css-loader',
                     'less-loader',
                 ],
             }, { // webpack5 does not recognize these files by default, so just output them as static resources test: /\.(eot|svg|ttf|woff|woff2)$/,
                 type: 'asset/resource',
                 generator: {
                     filename: 'font/[name].[hash:6][ext]'
                 }
             }],
     },
};

Notice:

  • HtmlWebpackPlugin introduces the css file into the packaged html page in the form of a link.
  • The use configuration items are from right to left.
  • When using css and less, that is, in the use configuration item, MiniCssExtractPlugin.loader must not be placed after css-loader and before style-loader, because css-loader and less-loader process @import and url(), just like js parses import/require() (placing it after it is equivalent to splitting it before parsing, which will result in an error). The style-loader inserts CSS into the DOM (placing it before it is equivalent to inserting the CSS into the DOM and then splitting it will result in an error).

3. Compress the split CSS files

  • Download optimize-css-assets-webpack-plugin
  • Import and configure the webpack.config.js file
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
//Introduce the installed mini-css-extract-plugin
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
//CSS used to compress the split
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
module.exports = {
    //Entry file address entry: './src/index1.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        //Export file name filename: 'bundle.js',
    },
    plugins: [new MiniCssExtractPlugin(),new OptimizeCSSAssetsPlugin({}),
        new HtmlWebpackPlugin({
        template: './public/interlaced color.html'
    })],
     module: {
         rules: [{
             //Match files ending with .css, i is case insensitivetest: [/\.css$/i],
            //Execute from right to left, the order cannot be changed. Style-loader inserts CSS into DOM, and css-loader processes @import and url(), just like js parses import/require(). use: [MiniCssExtractPlugin.loader, "css-loader"
             ],
         }, {
             test: /\.less$/i,
                 use: [
                     // compiles Less to CSS 
                     MiniCssExtractPlugin.loader,
                     'css-loader',
                     'less-loader',
                 ],
             }, { // webpack5 does not recognize these files by default, so just output them as static resources test: /\.(eot|svg|ttf|woff|woff2)$/,
                 type: 'asset/resource',
                 generator: {
                     filename: 'font/[name].[hash:6][ext]'
                 }
             }],
     }
};

4. Packaging

I found an extra main.css file and opened the webpage to view it:

The main.css file is imported as a link and compressed.

This is the end of this article about webpack splitting and compressing CSS and importing it with link. For more relevant webpack splitting and compressing CSS content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Solution to webpack4 css packaging compression problem
  • Example of how to package and compress js and css with webpack

<<:  Detailed tutorial on running multiple Springboot with Docker

>>:  HTML table markup tutorial (15): table title

Recommend

Summary of Problems in Installation and Usage of MySQL 5.7.19 Winx64 ZIP Archive

Today I learned to install MySQL, and some proble...

Thirty HTML coding guidelines for beginners

1. Always close HTML tags In the source code of p...

Linux bridge method steps to bridge two VirtualBox virtual networks

This article originated from my complaints about ...

Implementation code for adding links to FLASH through HTML (div layer)

Today a client wants to run an advertisement, and ...

Why should css be placed in the head tag

Think about it: Why should css be placed in the h...

Detailed explanation of Vue login and logout

Table of contents Login business process Login fu...

Solution to the lack of my.ini file in MySQL 5.7

What is my.ini? my.ini is the configuration file ...

CSS3 realizes the childhood paper airplane

Today we are going to make origami airplanes (the...

This article will help you understand JavaScript variables and data types

Table of contents Preface: Kind tips: variable 1....

Vue implements countdown function

This article example shares the specific code of ...

MySQL slow query method and example

1. Introduction By enabling the slow query log, M...

Beginners learn some HTML tags (1)

Beginners can learn HTML by understanding some HT...

How to automatically backup mysql remotely under Linux

Preface: Basically, whether it is for our own use...