webpack4.0 Conquer (2)--css

Source: Internet
Author: User
Tags postcss

webpackAs the most fire-front building tool, is the most important part of the front-end automation tool chain, the use of high threshold. This series is the author's own study record, compares the foundation, hoped through the problem + solves the pattern, takes the front-end construction to meet the concrete demand as the starting point, the Learning webpack tool corresponding processing method. (The parameter configuration and usage methods in this article are based on webpack4.0版本 )

A. css file basic processing requirements

Assuming that the CSS files in the project are written in a precompiled language, the basic issues that need to be addressed in packaging include:

    • Precompiled Language Conversion
    • Style file mount mode selection
    • Code optimization (merging and compression)
    • Remove or preserve annotations in a specified format
    • Conversion of resource location paths
    • Responsive layout unit conversion "optional"
    • Modular "optional"
    • Handling browser-compatible "optional"
Two. Upgrade the solution
  • Legacy Solution : Precompiled language + naming methodology

    In the era of not using build tools, developers use precompiled languages to implement variable definitions. Selectors nested and so on, and then use function function to achieve some more complex requirements, such as writing a simple @mixin px2rem () function to convert the PX units used in development to REM units, to achieve the purpose of mobile self-adaptation, or write some functions that deal with compatibility to handle browser compatibility. The

    is named with a number of methodologies, the most popular being BEM , which is named by the **block__element-modifier**, and a fragmented style of Aotm-css and object-oriented oocss , among other things, are named methodologies and mean there are no hard-to-detect and preventative measures.

  • New Solution : + + + + 预编译语言 构建工具 BEM + ACSS全局样式 CSSModule组件样式POSTCSS

    The use of precompiled languages is basically the same, but in modern development it is no longer necessary to solve the problem of unit conversions or compatibility by predefined functions. First, the build tool can transform the precompiled language into a CSS feature based on a modern build tool through automated detection, which solves the CSS-Module CSS modularity problem through a specific syntax, and the POSTCSS implementation-based autoprefixer plug-in You can automate the cross-browser prefix of your code based on the browser support data provided by the caniuse Web site.

    The new scheme involves a lot of new concepts, but it's not a simple technique, every concept has advantages and applications, you need to use the right technology in the right place, and the stupidest thing to do is to blindly ask developers to use the whole project because of a technology hit.

Three. Basic use Method 3.1 common plug-in and function brief

Take webpack4.0 the version as an example to demonstrate how the CSS module is handled, the plug-ins and functions that need to be used are as follows:

    • style-loader--Store the finished CSS code in JS, and mount it to the <style> page when the runtime is embedded html
    • css-loader--loader, enabling the webpack module to be identified css
    • postcss-loader--loader, the next article will be described in detail
    • sass-loader--loader to make webpack recognizable scss/sass files, compiled by default use node-sass
    • mini-css-extract-plugin--plugin, 4.0 version enabled plug-in, instead of the original extract-text-webpack-plugin plugin, the processed CSS code extracted into a separate CSS file
    • optimize-css-assets-webpack-plugin--Plugin to implement CSS code compression
    • autoprefixer--automated addition of cross-browser compatible prefixes
Configuration of the 3.2 webpack

This is not a webpack tutorial, here is a direct presentation of the annotated webpack.config.js configuration for reference, the example used SCSS as a precompiled language, the other preprocessing language configuration is basically the same:

Const Htmlwebpackplugin = require (' Html-webpack-plugin ');//plugin for automatic generation of HTML entry files const MINICSSEXTRACTPLUGIN = require (" Mini-css-extract-plugin ");//plugin for extracting CSS code as a standalone file const Optimizecssassetsplugin = require (" Optimize-css-assets-webpack-plugin ");//css module Resource Optimization Plugin module.exports = {mode: ' Development ', entry: './main.js ', Output:        {filename: ' main.bundle.js ', Path:__dirname + '/build '}, module: {rules: [{test:/\.scss$/, Exclude:/node_modules/,//Exclude Node_modules folder use: [{loader:minicssextractplugin.loader//recommends that the production environment adopt this Mode decoupling CSS file with JS file},{loader: ' Css-loader ',//css loader options: {importloaders:2}//designated Css-loader place  The maximum number of loader can pass before the},{loader: ' Postcss-loader ',//load Autoprefixer function},{Loader: ' Sass-loader '//scss loader, Webpack compiled by default with Node-sass}]}]}, plugins:[new Htmlwebpackplugin (),//Generate the Portal HTML file New Minicssextractplugin ({filename: "[name].CSS "})//For the extracted independent CSS file setting configuration parameters], optimization:{//For the generated CSS file code compression mode= ' production ' in effect minimizer:[new O Ptimizecssassetsplugin ()]}}

postcss.config.jsConfiguration is simple:

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

package.jsonAdd a new parameter to specify the type of browser that needs to be supported for packaging:

  "browerslist": [    "last 2 versions",    "IE 8",    "UCAndroid"  ]

Write a section to SCSS code:

//变量定义$grey: #1e1e1d;$yellow: #ffad15;$offwhite: #f8f8f8;$darkerwhite: darken($offwhite, 15);//SCSS函数$baseFontSize:14px;//循环@for $i from 1 through 3 {  .item-#{$i} { width: 2em * $i; }}//mixin@mixin px2rem($name, $px){  #{$name}: $px / $baseFontSize * 1rem;}//嵌套.class3{    font-weight: bold;    display:flex;    &-small{        color: $offwhite;        @include px2rem('font-size',14px);    }}//autoprefixer::placeholder{    width:10px;}

You can see the converted results:

Tip: Optimizations such as code compression are enabled by default when mode: ' Production ' is available in version 4.0.

Four. Using Css-modules

Project Address: CSS modules Open Source Address

The CSS Module uses the class selector in CSS, which is based on replacing the style name in the CSS code with a hash value and creating a json table that is js replaced with the use of the property name selector in the file. Hash string , which solves the problem of CSS modularity.

The ability to use CSS Modules features in Webpack is very simple and only needs to be css-loader set in the configuration parameters:{modules:true} to activate the modular function.

After you turn on the modular function and then package, you can see that the same main.css file looks like this:

The following fragment is added to the package file:

Of course CSS Modules the usage is much more than that, more information can be found in the project address above.

Five. Graphic Css-process-chain

As can be seen from the above configuration, the use of pre-compiler writing style files need to go through a series of loader and plugin to get the final target file, it is very abstract because the middle of the processing link to the developer is a black box operation, only to see the input and output, the author combined with their own understanding of the drawing of the following, Hopefully it will help you understand how CSS files are webpack handled throughout the packaging process ( plugins some have not yet been researched and are not covered in the processing chain).

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.