WEBPACK4 Series Tutorial (eight): CSS Tree Shaking

Source: Internet
Author: User
Tags glob
    • The picture shown in the tutorial is a github warehouse image, please visit the original address of a friend with slow speed
    • Take a look at the personal tech Station when you're free.
0. Course presentation and information

The code catalog for this course (as shown):

>>> the source of this lesson

>>> All courses Source code

1. CSS also has a Tree Shaking?

Yes, with the rise of Webpack, CSS can also be used for Tree Shaking: To remove CSS styles that are not available in the project code, and to keep only the style code that is in use.

To facilitate understanding of the tree Shaking concept and to compare it with the JS tree Shaking, see: Webpack4 Series Tutorial (eight): JS tree Shaking

2. Project Environment Simulation

Because the CSS tree Shaking is not as easy to understand as JS Tree Shaking, first of all, we need to simulate a real project environment to embody the configuration and effect of the CSS tree Shaking.

We first wrote the /src/css/base.css style file, and in the file we wrote 3 style classes. But in the code, we only use .box .box--big these two classes. The code looks like this:

/* base.css */html {  background: red;}.box {  height: 200px;  width: 200px;  border-radius: 3px;  background: green;}.box--big {  height: 300px;  width: 300px;  border-radius: 5px;  background: red;}.box-small {  height: 100px;  width: 100px;  border-radius: 2px;  background: yellow;}

According to normal usage, DOM operation to implement the style of adding and unloading, is a consistent technical means. So, /src/app.js a tag is created in the portal file <div> , and its class is set to.box

// app.jsimport base from "./css/base.css";var app = document.getElementById("app");var div = document.createElement("div");div.className = "box";app.appendChild(div);

Finally, in order to get the environment closer to the real world, we have index.html a label that references a well-defined box-big style class.

<!DOCTYPE html>

According to our simulation environment, the effect after the final Tree Shaking should be: the packaged CSS file does not contain box-small style classes . Below, this effect is achieved!

3. Recognize the following PurifyCSS

That's right, it's the stuff that helps us with the CSS Tree Shaking operation. It also has good friends glob-all (another third party libraries) in order to accurately indicate the CSS file to be Shaking the Tree.

glob-allThe function is to help with PurifyCSS path processing, locating the path file to be the tree Shaking.

They both match up and draw the following winds:

const PurifyCSS = require("purifycss-webpack");const glob = require("glob-all");let purifyCSS = new PurifyCSS({  paths: glob.sync([    // 要做CSS Tree Shaking的路径文件    path.resolve(__dirname, "./*.html"),    path.resolve(__dirname, "./src/*.js")  ])});

Well, it's just a little demo. Now we're going to use it in our own webpack.config.js .

4. Writing the configuration file

This plugin is also used in the configuration to facilitate the final inspection of the packaged CSS file extract-text-webpack-plugin . If you have forgotten how to use it, please check:

    • Webpack4 Series Tutorial (vi): processing SCSS
    • Webpack4 Series Tutorial (v): Working with CSS

So, our package.json file is as follows:

{  "devDependencies": {    "css-loader": "^1.0.0",    "extract-text-webpack-plugin": "^4.0.0-beta.0",    "glob-all": "^3.1.0",    "purify-css": "^1.2.5",    "purifycss-webpack": "^0.7.0",    "style-loader": "^0.21.0",    "webpack": "^4.16.0"  }}

After installing the relevant plug-in, we need to refer to the third part of the code defined in Webpack's plugins configuration.

Then combine extract-text-webpack-plugin the configuration and write the following webpack.config.js :

Webpack.config.jsconst path = require ("path"), const PURIFYCSS = require ("Purifycss-webpack"), const GLOB = require (" Glob-all "), const Extracttextplugin = require (" Extract-text-webpack-plugin "); let Extracttextplugin = new    Extracttextplugin ({filename: "[name].min.css", allchunks:false}); let purifycss = new Purifycss ({Paths:glob.sync ([ To do CSS tree shaking path file Path.resolve (__dirname, "./*.html"),//Please note that we also need to Tree the HTML file shaking Path.resolve (__dirname, "./src/*.js")]); Module.exports = {entry: {app: "./src/app.js"}, Output: {publicpath: __dirname + "/dist/", Path:path.reso      Lve (__dirname, "dist"), FileName: "[name].bundle.js", Chunkfilename: "[name].chunk.js"}, module: {rules: [ {test:/\.css$/, Use:ExtractTextPlugin.extract ({fallback: {loader: "Style-loader") , options: {singleton:true}}, use: {loader: "Css-load          Er ",  Options: {Minimize:true}}}}]}, plugins: [Extracttextplugin, P URIFYCSS]};
5. Results analysis

After the command line runs webpack packaged, the style file is extracted to the /dist/app.min.css file. File content as shown ( sure many friends lazy to pack manually ):

The styles we index.html quoted in and are packaged, and the style classes that are src/app.js not used--are box-small not appearing in the picture. Success!

End

Welcome into the group:857989948 . IT technology in-depth communication and sharing, including but not limited to: website production, operations, UI design, algorithmic analysis, big data, artificial intelligence and so on. This group has the depth, the attitude of technical exchanges, welcome to record knowledge of your participation.

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.