Webpack4 Series Tutorial (v): Working with CSS

Source: Internet
Author: User

This lesson explains the webpack4 packaged css apps. There are no special discrepancies between the V4 version and the V3 version.

>>> the source of this lesson

>>> All courses Source code

The picture shown in the tutorial is a github warehouse image, a friend with a slow speed, please go to >>> the original address. comments or the latest updates, please also visit.

1. Preparatory work

As we all know, CSS in the common introduction of HTML methods are <link> labeled and <style> tagged two, so this is the combination of webpack features to achieve the following functions:

    1. Introducing CSS through the link tag
    2. Put CSS in the Style tab
    3. dynamically unload and load CSS
    4. Page before the CSS is loadedtransform

This shows the structure of the Directory code:

This time we need to use css-loader , file-loader such as LOADER, as package.json follows:

{  "devDependencies": {    "css-loader": "^1.0.0",    "file-loader": "^1.1.11",    "style-loader": "^0.21.0"  }}

Where the base.css code is as follows:

*,body {  margin: 0;  padding: 0;}html {  background: red;}

index.htmlThe code is as follows:

<!DOCTYPE html>
2. CSSPass <link>Label Introduction

The link tag refers to a CSS file, so you need file-loader to use it to process the CSS as a file.

webpack.config.js:

const path = require("path");module.exports = {  entry: {    app: "./src/app.js"  },  output: {    publicPath: __dirname + "/dist/",    path: path.resolve(__dirname, "dist"),    filename: "[name].bundle.js"  },  module: {    rules: [      {        test: /\.css$/, // 针对CSS结尾的文件设置LOADER        use: [          {            loader: "style-loader/url"          },          {            loader: "file-loader"          }        ]      }    ]  }};

To make the effect more noticeable, write the following app.js :

let clicked = false;window.addEventListener("click", function() {  // 需要手动点击页面才会引入样式!!!  if (!clicked) {    import("./css/base.css");  }});
3. CSSPlaced in <style>In the label

In general, css style You can reduce the number of network requests and increase the response time by placing them in the tag. It is important to note that in older IE browsers, the style number of tags is required .

app.jsAs in the second part, the webpack.config.js configuration changes are as follows:

const path = require("path");module.exports = {  entry: {    app: "./src/app.js"  },  output: {    publicPath: __dirname + "/dist/",    path: path.resolve(__dirname, "dist"),    filename: "[name].bundle.js"  },  module: {    rules: [      {        test: /\.css$/, // 针对CSS结尾的文件设置LOADER        use: [          {            loader: "style-loader",            options: {              singleton: true // 处理为单个style标签            }          },          {            loader: "css-loader",            options: {              minimize: true // css代码压缩            }          }        ]      }    ]  }};
4. Dynamic Unload and load CSS

style-loaderThere are two ways to provide CSS objects use() unuse() , and with these two methods, you can easily and quickly load and unload CSS styles.

First, you need to configure webpack.config.js :

const path = require("path");module.exports = {  entry: {    app: "./src/app.js"  },  output: {    publicPath: __dirname + "/dist/",    path: path.resolve(__dirname, "dist"),    filename: "[name].bundle.js"  },  module: {    rules: [      {        test: /\.css$/,        use: [          {            loader: "style-loader/useable" // 注意此处的style-loader后面的 useable          },          {            loader: "css-loader"          }        ]      }    ]  }};

Then we modify our to app.js achieve a background color change every 0.5s:

import base from "./css/base.css"; // import cssObj from '...'var flag = false;setInterval(function() {  // unuse和use 是 cssObj上的方法  if (flag) {    base.unuse();  } else {    base.use();  }  flag = !flag;}, 500);

After packaging index.html , you can see the color of the page background flashing.

5. Page loading cssBefore the transform

For css transform , simply put: you can change the CSS before you load the CSS style. This makes it easy for developers to handle CSS based on their business needs.

You need to add the attribute to the style-loader options.transform specified JS file, so the webpack.config.js configuration is as follows:

const path = require("path");module.exports = {  entry: {    app: "./src/app.js"  },  output: {    publicPath: __dirname + "/dist/",    path: path.resolve(__dirname, "dist"),    filename: "[name].bundle.js"  },  module: {    rules: [      {        test: /\.css$/,        use: [          {            loader: "style-loader",            options: {              transform: "./css.transform.js" // transform 文件            }          },          {            loader: "css-loader"          }        ]      }    ]  }};

Below, we write css.transform.js , this file exports a function, the passed parameter is the CSS string itself.

module.exports = function(css) {  console.log(css); // 查看css  return window.innerWidth < 1000 ? css.replace("red", "green") : css; // 如果屏幕宽度 < 1000, 替换背景颜色};

To app.js introduce a CSS file in, you can:

import base from "./css/base.css";

We open the console, as shown, when the screen width is less than 1000, the CSS red has been replaced in order to green .

It is important to note that transform it is modified as needed before the introduction of the CSS, so it will not change. So the above code is not responsive, and when the width of the screen is longer than 1000, it is still green. Re-refresh the page before it will be red.

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.