1. Write in front

In the previous blog, I gave a brief introduction to the WebPack packaging project, and it was all about packaging and compiling.js files. We know that in a Webpack-based project, there are not only.js files, but also.html,.css,.png files. In this blog, we will show you how to use WebPack to compile.css files.

The main contents include:

  • How do I introduce.css files into my project

  • Package and compile.css files

  • Package and compile.less files

  • Detach the CSS code into a single file

  • Add a relevant prefix to the packaged compiled CSS3 attribute

  • Compress the compiled.css file

2. How to introduce it into the project.cssfile

As mentioned earlier, WebPack packages and compiles the project files in your project, and then mounts the generated files into an.html template file. At this point, if you want to introduce a CSS style, you might think: I’ll just write the CSS style directly to the.html template file, or I’ll just mount the.css file to the template file. For example, the following code:


      
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        body {
            background-color: red;
            color: yellow;
        }
    </style>
</head>
<body>

    <h1>This is a template file</h1>
    
</body>
</html>
Copy the code

First of all, it works functionally. Whether you use Yarn Dev to start a development server or yarn Build to package a project, the style you write will exist and work. However, this method is very bad and not standard, so it is highly recommended. So how do you introduce CSS code?

If you are building a project using Vue or React scaffolding, you can use their official tutorial to write CSS styles. If you are building a project manually from scratch, you can use.css files in.js files, such as the following example:

/ / index. Js file
console.log('I am the index.js file');

require('./index.css')  // Import the.css style file

require('./b.less')     // Import the.less style file
Copy the code
/* index.css file */
body {
    background-color: red;
    color: yellow;
}
Copy the code
/* the b.ess file */
body {
    border: 5px solid # 45454;
    div {
        font-size: 20px;
        font-weight: bolder; }}Copy the code

We have now introduced.css and.less files into the project, but at this point, if we start the local development server or package and compile the project, we will definitely get an error.

This is because we haven’t done the configuration yet, and WebPack doesn’t know what to do with these imported files. The next thing to talk about is how to configure WebPack to package and compile style files.

3. Package and compile.cssfile

Webpack is able to package and compile a wide variety of files in a project because it makes use of many powerful plug-ins or modules. So if we want to package and compile.css, first install two Loader modules: csS-Loader and style-Loader. The installation command is as follows:

yarn add css-loader style-loader -D
Copy the code

After the installation is complete, we will configure the webpack.config.js file. Here we will show the standard configuration code and then go into more detail (focus on the commented parts) :

let path = require("path");
let HtmlWebpackPlugin = require("html-webpack-plugin")

module.exports = {
    mode: "development".entry: "./src/index.js".output: {       
        filename: "index.js".//
        path: path.resolve(__dirname, "build")},plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html'.filename: 'index.html'.minify: {
                removeAttributeQuotes: true.collapseWhitespace: true
            },
            hash: true}),].module: {       // Configure the modules used by WebPack
        rules: [
            {
                test: /\.css$/.// For files ending in.css, use the following loader
                use: [
                    'style-loader'.'css-loader'[}],}}Copy the code

In the above code, we add the Module property, which is an object, which in turn has a rules property, which is an array. In this array, we can configure a number of rules to specify which programs to process the various files (such as which loader to use for processing, etc.). Here we first configure the handling rules for.css.

Configuring rules in the Rules array is as simple as adding an object. To configure rules for handling.css files, as shown in the above code, add the following objects:

{
    test: /\.css$/.// For files ending in.css, use the following loader
    use: [
        'style-loader'.'css-loader']}Copy the code

This object has two properties: test and use

  • The test property is used to match files. Normally, we use regular expressions to match files. In the above code, /\.css$/ matches files ending in.css.

  • The use attribute specifies which programs are used to process the matched file. This property is an array because there are many programs that can be used to process a single file. For example, in the code above, we specify that we use style-loader and css-loader to process.css files, and we need to write both programs to the array.

    It is important to note that the order of the programs in this array cannot be arbitrary, because webPack will process the files from the back to the front, using the specified programs.

    For example, when processing the index. CSS file, use the CSS-Loader to process the CSS syntax, and then use the style-loader to mount the processed CSS to the index. HTML template file. When writing the use attribute, write the style-loader first and the CSS-loader second.

    Finally, you can write objects as well as strings in this property to further configure the loader program that handles files. For example, if you want to mount the processed CSS to the top of the template file, you can configure it like this:

    {
        test: /\.css$/.use: [{loader: 'style-loader'.options: {
                    insertAt: 'top'	// Mount the compiled CSS to the top of the template file}},'css-loader']},Copy the code

    If you do not know how to write a property, you can use the official loader document, such as the official styleloaderde document.

After configuring these rules, start the local development server using Yarn Dev or package and compile the project using Yarn Build. Webpack can smoothly process the.css file using our configured rules.

4. Package and compile.lessfile

If the project uses less syntax (a CSS preprocessor language), we need to configure the rules for handling.less files. Similar to handling.css files, you should install two modules: less and less-loader. The installation command is as follows:

yarn add less less-loader -D
Copy the code

The configuration method is the same as above, so here is the code for the configuration (focus on the commented parts) :

let path = require("path");
let HtmlWebpackPlugin = require("html-webpack-plugin")

module.exports = {
    mode: "development".entry: "./src/index.js".output: {        
        filename: "index.js".path: path.resolve(__dirname, "build")},plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html'.filename: 'index.html'.minify: {
                removeAttributeQuotes: true.collapseWhitespace: true
            },
            hash: true}),].module: {       // Configure the modules used by WebPack
        rules: [
            {
                test: /\.css$/.// For files ending in.css, use the following loader
                use: [
                    'style-loader'.'css-loader'] {},test: /\.less/.use: [
                    'style-loader'.'css-loader'.'less-loader'       // Less-loader converts the less syntax to the normal CSS syntax[}],}}Copy the code

Once the configuration is complete, restart the development server or repackage the compilation, and the.less file will compile smoothly.

5. Separate the CSS code into a single file

As mentioned earlier, WebPack packs and compiles.css or.less files to mount the processed CSS code into the template file, but sometimes we don’t want to do this. We want to output the processed CSS code to a specified file, which is then automatically imported into the template file. To achieve this, perform the following configuration:

Install the mini-css-extract-plugin plugin using the following command:

yarn add mini-css-extract-plugin -D
Copy the code

After the installation is complete, go directly to the following configuration (focus on the annotated parts) :

let path = require("path");
let HtmlWebpackPlugin = require("html-webpack-plugin")
let MiniCssExtract = require('mini-css-extract-plugin') // Import the plugin

module.exports = {
    mode: "production".entry: "./src/index.js".output: {
        filename: "index.js".path: path.resolve(__dirname, "build")},plugins: [		// Configure the plug-in
        new HtmlWebpackPlugin({
            template: './src/index.html'.filename: 'index.html'.minify: {
                removeAttributeQuotes: true.collapseWhitespace: true
            },
            hash: true
        }),
        new MiniCssExtract({ 		// Create an instance of the plug-in
            filename: 'main.css' 	// Specify the name of the output CSS file})].module: {
        rules: [{
                test: /\.css$/.use: [
                    MiniCssExtract.loader, // Configure the rule to output the processed CSS code directly to the specified file
                    'css-loader'.'postcss-loader'] {},test: /\.less$/.use: [
                    MiniCssExtract.loader, // Configure the rule to output the processed CSS code directly to the specified file
                    'css-loader'.'less-loader'.'postcss-loader'[}]}Copy the code

After the configuration is complete, package and compile the project with Yarn build. A main. CSS file is obtained, which contains the compiled CSS code.

/* main. CSS file */
body {
    color: yellow;
}
body {
    background-color: gray;
    transform: rotate(45deg)	/* Note that this line of css3 code has no prefix. */ is mentioned later
}
body {
  border: 5px solid # 4545 4;
}
body div {
  font-size: 20px;
  font-weight: bolder;
}
Copy the code

See the mini-css-extract-plugin official documentation for more information on how to configure this section

6. Add prefixes to the packaged and compiled CSS properties

As shown in the main.css code shown above, some CSS3 properties are not prefixed in the compiled code, which in some cases may not be sufficient for your project. If we want to automatically prefix compiled CSS3 attributes, we can do the following configuration:

Start by installing two Loader programs: PostcsS-Loader and autopreFixer. The installation command is as follows:

yarn add postcss-loader autoprefixer -D
Copy the code

When the installation is complete, first configure the webpack.config.js file as follows (focus on the commented sections) :

let path = require("path");
let HtmlWebpackPlugin = require("html-webpack-plugin")
let MiniCssExtract = require('mini-css-extract-plugin')

module.exports = {
    mode: "production".entry: "./src/index.js".output: {  
        filename: "index.js".path: path.resolve(__dirname, "build")},plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html'.filename: 'index.html'.minify: {
                removeAttributeQuotes: true.collapseWhitespace: true
            },
            hash: true
        }),
        new MiniCssExtract({
            filename: 'main.css'})].module: {
        rules: [{
                test: /\.css$/.use: [
                    MiniCssExtract.loader,
                    'css-loader'.'postcss-loader'        // Add a prefix to the CSS3 attribute] {},test: /\.less$/.use: [
                    MiniCssExtract.loader,
                    'css-loader'.'less-loader'.'postcss-loader'    	// Add a prefix to the CSS3 attribute[}]}Copy the code

In the code above, we specified to use postcss-Loader to handle.css and.less files, but webPack does not automatically prefix the CSS3 properties. We need to configure postcss-Loader. Create a postcss.config.js file in the project root directory and write the following configuration code in it:

module.exports = {
    plugins: [
        require('autoprefixer')]}Copy the code

Webpack automatically prefixes CSS3 properties, as shown in the following example:

/* main. CSS file */
body {
    color: yellow;
}
body {
    background-color: gray;
    -webkit-transform: rotate(45deg);
            transform: rotate(45deg)
}
body {
  border: 5px solid # 4545 4;
}
body div {
  font-size: 20px;
  font-weight: bolder;
}
Copy the code

7. Compress the compiled version.cssfile

In the previous section, you saw that the detached main.css file was not compressed, but many projects need to compress the.css file to save volume when packaging. To do this, configure the following:

First install a plug-in: optimism-CSS-assets – Webpack-plugin. The installation command is as follows:

yarn add optimize-css-assets-webpack-plugin -D
Copy the code

After the installation is complete, simply configure webpack.config.js as follows (focus on the annotated parts) :

let path = require("path");
let HtmlWebpackPlugin = require("html-webpack-plugin")
let MiniCssExtract = require('mini-css-extract-plugin')
let OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');    // Import the plugin

module.exports = {
    optimization: {     					// Configure webPack optimizations
        minimizer: [    					// Configure the minimum optimization item
            new OptimizeCSSAssetsPlugin()   // Declare an instance of the CSS optimization plug-in]},mode: "production".entry: "./src/index.js".output: {  
        filename: "index.js".path: path.resolve(__dirname, "build")},plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html'.filename: 'index.html'.minify: {
                removeAttributeQuotes: true.collapseWhitespace: true
            },
            hash: true
        }),
        new MiniCssExtract({
            filename: 'main.css'})].module: {
        rules: [{
                test: /\.css$/.use: [
                    MiniCssExtract.loader,
                    'css-loader'.'postcss-loader'] {},test: /\.less$/.use: [
                    MiniCssExtract.loader,
                    'css-loader'.'less-loader'.'postcss-loader'[}]}Copy the code

Once the configuration is complete, package and compile the project again, and you get the compressed main.css file.

It is important to note that in the configuration above, although we specified production mode for WebPack, where the packaged.js file should be compressed, this is not the case and the resulting.js file is not compressed.

This is because when we configure WebPack optimizations, some of the optimizations overwrite the default webPack configuration. We didn’t specify compressed.js files here, so even if we package and compile in production mode, we’ll still end up with uncompressed.js files.

If you want to compress.js files, it’s very simple, just like configuring.css compression. The configuration is as follows:

First install a plugin: terser-webpack-plugin

yarn add terser-webpack-plugin -D
Copy the code

Then do something similar to the above configuration (focus on the annotated sections) :

let path = require("path");
let HtmlWebpackPlugin = require("html-webpack-plugin")
let MiniCssExtract = require('mini-css-extract-plugin')
let OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');   
let TerserJSPlugin = require('terser-webpack-plugin');      // Import the plugin

module.exports = {
    optimization: {                         // Configure webPack optimizations
    minimizer: [                            // Configure the minimum optimization item
            new OptimizeCSSAssetsPlugin(),
            new TerserJSPlugin()            // Declare an instance of the JS compression plug-in]},mode: "production".entry: "./src/index.js".output: {  
        filename: "index.js".path: path.resolve(__dirname, "build")},// To save space, I will not write the following configuration, as above
}
Copy the code

Now package it again, and the resulting.js file is compressed.

8. Put it at the end

This blog post is a bit more than that, focusing on how to configure rules for handling.css files in WebPack. I hope it helps.

Install and configure the WebPack development server

Learn Note 06 — Compiling JS files with Babel packages