Using POSTCSS to compress and optimize CSS instances

Source: Internet
Author: User
Tags http request postcss

Click here for information on how to use the Postcss plugin across browsers: http://www.111cn.net/cssdiv/css/98338.htm


The main contents of this article are:

By @import multiple styles into one, even though some of your styles come from Bower components or NPM modules, you can ensure that you only need to request a separate HTTP to load the Web site's CSS; match media queries that allow you to combine multiple locations using the same media query into a Use Cssnano to perform various optimizations, remove whitespace and annotations, and compress code.

set up the project

The first thing you need to do is to use Gulp or grunt to set up your project. If you don't have a good project template, you can use Gulp or grunt to use minimal code to achieve the same goal.

If you do not want to manually set up your project from scratch, you can download the source attachment provided in this tutorial, extract Gulp or grunt items into an empty folder.

Then run at the command terminal: NPM install.

Installing Plug-ins

In this tutorial we will use two separate plug-ins, plus a plug-in package. Install the plugin to your project folder by running the following command:

NPM Install Postcss-import css-mqpacker Cssnano--save-dev

Now that the plugin has been installed, let's continue to add the required configuration to the project.

using Gulp to load Plug-ins

If you use Gulp, you can add the following variable to your Gulpfile.js file:

var atimport = require (' Postcss-import ');
var mqpacker = require (' Css-mqpacker ');
var Cssnano = require (' Cssnano ');

and add the following variable name to the processors array:

var processors = [
Atimport,
Mqpacker,
Cssnano
];

With the Gulp CSS command you can do a quick test and you can see the Dest folder in your project to add style.css files.

adding plug-ins using grunt

If you are using the Grunt Setup project, you can add the following variable name to the processors object in your Gruntfile.js file and give the corresponding options parameter:

Processors: [
Require (' Postcss-import ') (),
Require (' Css-mqpacker ') (),
Require (' Cssnano ') ()
]

Perform a grunt postcss command at the command terminal to make a quick test. Check to see if the Style.css file is added to the Dest folder of your project.

All the required plug-ins are installed and loaded into the project, so let's continue to learn how to use them to compress and optimize CSS.

using @import to compress files

Most of the time, your project not only loads a style sheet, but it loads multiple stylesheets. To be able to load styles more efficiently, you should merge the style sheets into one as much as possible.

For example, NORMALIZE.CSS is a very common style sheet, and if it is loaded as a separate style sheet before the main style, there is an extra HTTP request, which slows down load time.

Using the Postcss-import plug-in for @maxime Thirouin, follow the @import rules, you can merge the NORMALIZE.CSS style into your main stylesheet, so that loading the same CSS requires only one HTTP request.
Using @import inline loading normalize.css

Now let's take a look at how to merge normalize.css into the main style sheet through @import in the project. First you need to download the Normalize.css file and put it in the SRC folder in your project.

Next, add the following code to the top of the Src/style.css file:

@import ' Normalize.css ';

When you install the Postcss-import plug-in, it detects the Normalize.css file @import introduced in the main style sheet and automatically merges the NORMALIZE.CSS style into your stylesheet.

After compiling, you should see the NORMALIZE.CSS style code in the Dest/style.css file:

/*! Normalize.css v3.0.2 | MIT License | Git.io/normalize */html{font-family:sans-serif .....

You can use the same method to combine as many independent styles as possible. You only need to introduce the standalone stylesheet that you want to merge through the @import in the Src/style.css file.
Automatic discovery of Style files in Bower Component and Node module

This plugin also has a very useful feature that automatically discovers the CSS file location within the Bower_components or Node_modules folder.

As mentioned above, you do not need to manually install NORMALIZE.CSS, you only need to execute the Bower install normalize.css--save command at the command line, you can install the file into your project. This time will automatically download the latest normalize.css to the Bower_components/normalize.css folder.

Note: If you do not have Bower installed in your computer, you can click here to find out.

At the top of your stylesheet, use the code above to override:

@import ' Normalize.css/normalize.css ';

The Postcss-import plugin finds the Normalize.css file in your Bower_components folder, and then merges the code into the main style sheet.

In the same way, the styles in the Node_modules folder can be introduced into the stylesheet, which means that you can use Bower or NPM downloads to manage dependencies and updates. The plug-in service is very simple, that is, you can merge Third-party CSS style files into your style sheet.
Methods for importing styles in @import lines

By @import you can import CSS files from different sources, such as bower_components/, into the stylesheet, so that you can separate and manage styles separately.

For example, you can create a file to control your layout and create a separate file to manage your color scheme. If you want to change your color scheme, you just need to follow the same process:

The original style sheet that declares the color
Modify new color code
Import a new color style sheet into your project
Compile create alternate color style sheet

You can repeat this process so that you can create a more efficient color scheme.

Some projects use different style sheets to provide multiple such color schemes, but this increases the HTTP request and affects the speed at which the site is loaded. With this approach you always end up asking for only one HTTP.

For more information on Postcss-import, click here to learn more.

combine a matching media query

@Kyo Nagashima Css-mqpacker plug-in can find the same media query style in the stylesheet merged into a single media query. This allows you to write CSS, the media query can be repeatedly written, you do not have to worry about this will create a redundant code of your style, and affect your efficiency.

Let's look at a simple example where you might want to repeat a media query, such as writing your layout based on visual effects. In the actual project, you might give the layout a single style file, but for simplicity's sake, we'll put the code in the Src/style.css file.

Start with some layout code. A. Column class is added and its width is set to 50%, and by default, the two columns are lined together. Then use a media query that, under the smaller screen, arranges them from top to bottom. Add the following code to your style sheet:

* LAYOUT * *

. column {
width:50%;
Float:left;
}

@media (Max-width:50rem) {
. column {
width:100%;
Float:none;
}
}

Next, add some visual effects, such as setting a gray border on the column. The first column uses the class name. Column_one, and the second column uses the class name. Column_two. We use the same media query to change the border style based on the layout of the columns.

Add the following code to your style:

* Visuals * *

. Column_one,. column_two {
Border:0.0625rem solid #ccc;
}

. column_two {
border-left:0;
}

@media (Max-width:50rem) {
. Column_one,. column_two {
Border:0.0625rem solid #ccc;
}

. column_two {
border-top:0;
}
}

Recompile the Src/style.css file, and you can see the compiled code in DEST/STYLE.CSS.

As the following code shows, the Css-mqpacker plug-in has confirmed that two media queries are the same and grouped them together:

* LAYOUT * *

. column {
width:50%;
Float:left;
}

* Visuals * *

. Column_one,. column_two {
Border:0.0625rem solid #ccc;
}

. column_two {
border-left:0;
}

@media (Max-width:50rem) {

. column {
width:100%;
Float:none;
}

. Column_one,. column_two {
Border:0.0625rem solid #ccc;
}

. column_two {
border-top:0;
}
}

Note: The DEST/STYLE.CSS code you see is compressed because of the use of the Cssnano plugin. You can annotate the Cssnano in the processors array in the Gulpfile.js or gruntfile.js file to see the uncompressed code above.

For more information on Css-mqpacker, click here to learn more.

Cssnano Plug-in Package

@Ben Briggs provides a very powerful CSS optimized plug-in package Cssnano, this plug-in package is one that can plug and play. It brings together about 25 plug-ins and can do a variety of different kinds of optimizations with only one command to execute.

Cssnano optimization includes some of the following types:

Delete a space and the last semicolon
Delete a comment
Optimize font weights
Discard duplicate style rules
Optimizing Calc ()
Compression Selector
Reduce handwriting Properties
Consolidation rules

Add some sample code to your project based on the above optimization list. Add the following code to the SRC/STYLE.CSS:

Css_nano,. Css_nano + P, [class*= "Css_nano"],. Css_nano {
/* This is a example of Cssnano in action * *
Font-weight:normal;
Margin-top:1rem;
Margin-bottom:2rem;
Margin-left:1.5rem;
Margin-right:2.5rem;
Font-weight:normal;
Padding:1.75rem;
Width:calc (50rem-(2 * 1.75rem));
}

A
Text-decoration:none;
Font-weight:bold;
}

p {
Font-weight:bold;
}

Then recompile your file.

Note: You can comment out other code so that you can see the results more clearly.

In the Dest/style.css file you can see the code code:

. Css_nano,.css_nano+p,[class*=css_nano]{margin:1rem 2.5rem 2rem 1.5rem;font-weight:400;padding:1.75rem;width : 46.5rem}a{text-decoration:none}a,p{font-weight:700}

Take a look at the code list mentioned in the list above, and then compare the sample code before and after compiling to see what has changed:

Spaces, comments, and last semicolon removed
Font-weight:normal and Font-weight:bold are compiled into font-weight:400 and font-weight:700
The second duplicate Font-weight:normal rule is removed from the. Css_nano style
Calc () value is processed as a static value
. Css_nano,. Css_nano + P, [class*= "Css_nano"],. Css_nano compressed to. Css_nano,.css_nano+p,[class*=css_nano]
Handwriting multiple attributes Margin-top:1rem; Margin-bottom:2rem; Margin-left:1.5rem; Margin-right:2.5rem processing into Margin:1rem 2.5rem 2rem 1.5rem;
Font-weight:700 of A and p; merging together

The full list of Cssnano plug-in optimizations can be clicked here.

Configuring parameters and disabling Modules

The Cssnano plug-in package contains a number of standalone plug-ins that you can configure or even disable entirely, depending on your requirements.

To disable the plugin, you can set its argument to False by Cssnano. For example, you do not want to optimize the font weight, you can set this in Gulpfile.js or gruntfile.js files:

In Gulpfile ' processors ' array
Cssnano ({
Minifyfontweight:false
})

In Gruntfile ' processors ' array
Require (' Cssnano ') ({
Minifyfontweight:false
})

You can configure the plug-in's selection in the same way, each with the plug-in name, and then set its options.

For example, when using Calc (), you can set the precision value of a decimal number (the amount after the decimal point). By default, Calc (100%/2.27) results in 36.23188%, and if you want to be accurate to the two digits after the decimal digit, you can do this:

In Gulpfile ' processors ' array
Cssnano ({
Calc: {Precision:2}
})

In Gruntfile ' processors ' array
Require (' Cssnano ') ({
Calc: {Precision:2}
})

The last Calc computed output value is 36.23%.

Summary

Based on what is described above, let's make a quick summary:

The Postcss-import plug-in provides a more efficient way to introduce inline style sheets
The Postcss-import plug-in can introduce a third-party style sheet, or it can use a style sheet from a bower_components or Npm_modules folder
The Postcss-import plug-in can split the style sheet into parts and then regroup them
The Css-mqpacker plugin allows you to combine multiple identical media queries together
The Cssnano plug-in brings together 25 different plug-ins, provides Plug and play, and gets the ability to compress and optimize style sheets
The Cssnano plug-in can configure the Plug-ins in the package according to your own requirements

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.