编程知识 cdmana.com

Webpack 4.0 breaks down (2) -- CSS

webpack As the hottest building tool in the front end , It's the front-end automation tool chain The most important part , High use threshold . This series is my own learning record , More basic , Hope to pass problem + Solution The pattern of , The specific requirements encountered in the previous end build are the starting point , Study webpack The corresponding treatment in the tool .( The parameter configuration and usage in this article are based on webpack4.0 edition

One . CSS Basic document processing requirements

Let's say... In the project CSS The files are written in pre compiled language , So the basic issues that need to be addressed in packaging include :

  • Precompiled language conversion
  • How to mount the style file
  • Code optimization ( Merge and compress )
  • Remove or retain comments in the specified format
  • The transformation of resource location path
  • Responsive layout unit conversion 【 Optional 】
  • modularization 【 Optional 】
  • Handle browser compatibility 【 Optional 】

Two . Solution upgrade

  • The old solution Precompiled language  +  Nomenclature methodology

    In the age of no build tools , Developers use precompiled languages to implement variable definitions , Selectors, nesting, and so on , Then use function functions to implement more complex requirements , For example, write simple @mixin px2rem( ) Function to integrate the px Unit to rem Company , To achieve the purpose of mobile self-adaptive , To handle the compatibility of some browsers or functions .

    There are a lot of nomenclature methodologies , The most popular is BEM, That is to use block__Element-Modifier This naming method is used to divide modules , There's also fragmentation Aotm-CSS And object-oriented OOCSS etc. , It's all a nomenclature methodology , It also means that there are no hard and fast detection and prevention measures .

  • New solutions Precompiled language  +  Building tools  + BEM + ACSS Global style +CSSModule Component style POSTCSS

    The use of precompiled languages is basically unchanged , But in modern development, it is no longer necessary to solve the problem of unit conversion or compatibility through predefined functions . First , Building tools The precompiled language can be converted to CSS, The construction of modern tools based on CSS-Module function , It can be solved by specific syntax CSS modularization The problem of , And based on POSTCSS Realized autoprefixer plug-in unit , It can be based on CanIUse The browser support data provided by the website realizes the automatic completion of cross browser prefix of the code .

    The new plan involves a lot of new concepts , But it's not a simple stunt , Each concept has its advantages and applicable occasions , You need to use the right technology in the right place , The stupidest way to do this is to blindly ask developers to use .

3、 ... and . Basic usage

3.1 Common plug-ins and function description

With webpack4.0 Version as an example to demonstrate CSS How modules are handled , The plug-ins and functions needed are as follows :

  • style-loader—— Will deal with the end of CSS The code is stored in js in , Run time embedding <style> Then mount to html On the page
  • css-loader—— loader , send webpack Can identify css modular
  • postcss-loader—— loader , The next article will describe in detail
  • sass-loader—— loader , send webpack Can identify scss/sass file , By default node-sass Compile
  • mini-css-extract-plugin—— plug-in unit ,4.0 Version enabled plug-ins , Surrogate extract-text-webpack-plugin plug-in unit , Will deal with the CSS The code is extracted as independent CSS file
  • optimize-css-assets-webpack-plugin—— plug-in unit , Realization CSS Code compression
  • autoprefixer—— Automatically add cross browser compatible prefixes

3.2 webpack Configuration of

This article is not webpack course , Here we give the annotated webpack.config.js For reference , Use... In the example SCSS As a precompiled language , The configuration of other preprocessing languages is basically the same :

const HtmlWebpackPlugin = require('html-webpack-plugin');// Used to automatically generate html Plugins for entry files 
const MiniCssExtractPlugin = require("mini-css-extract-plugin");// take CSS Code extraction as a separate file plug-in 
const OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin");//CSS Module resource optimization plug-in 

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// It is recommended that the production environment be decoupled in this way CSS File with the js file 
          },{
            loader: 'css-loader',//CSS loader 
            options: {importLoaders: 2}// Appoint css-loader The most you can go through before processing loader Number      
          },{
            loader: 'postcss-loader',// bearing autoprefixer function 
          },{
            loader: 'sass-loader'//SCSS loader ,webpack By default node-sass Compile 
          }
        ]
      }
    ]
  },
  plugins:[
      new HtmlWebpackPlugin(),// Generate entry html file 
      new MiniCssExtractPlugin({
        filename: "[name].css"
      })// For the extraction of independent CSS File settings configuration parameters 
  ],
  optimization:{
    // Pair generated CSS File code compression  mode='production' Effective when 
    minimizer:[
       new OptimizeCssAssetsPlugin()
    ]
  }
}

postcss.config.js The configuration is simple :

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

package.json Add a new parameter to specify the browser category to be supported by the package :

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

Write a paragraph to be SCSS Code :

// Variable definitions 
$grey: #1e1e1d;
$yellow: #ffad15;
$offwhite: #f8f8f8;
$darkerwhite: darken($offwhite, 15);//SCSS function 
$baseFontSize:14px;

// loop 
@for $i from 1 through 3 {
  .item-#{$i} { width: 2em * $i; }
}

//mixin
@mixin px2rem($name, $px){
  #{$name}: $px / $baseFontSize * 1rem;
}

// nesting 
.class3{
    font-weight: bold;
    display:flex;
    &-small{
        color: $offwhite;
        @include px2rem('font-size',14px);
    }
}

//autoprefixer
::placeholder{
    width:10px;
}

You can see the result of the transformation :

Tips : Code compression and other optimization functions in 4.0 The default version is mode : 'production' Effective when .

Four . Use CSS-Modules

Project address :CSS Modules Open source address

CSS Module stay CSS Class selectors are used in , The basic principle is that CSS Replace the style name in the code with the hash value , And create a json Comparison table , stay js For Property name selector The use of is replaced by Hash string , To solve that CSS The problem of modularity .

stay webpack Use in CSS Modules The function is very simple , Only need css-loader Set... In the configuration parameters of :{modules:true} To activate the modular function .

Turn on the modular function and then pack it , You can see the same main.css The file looks like this :

The following fragment has been added to the package file :

Of course CSS Modules There is more to it than that , See project address above for more information .

5、 ... and . The illustration Css-Process-Chain

As can be seen from the above configuration , Style files written with the precompiler go through a series of loader and plugin To get the final target file , The reason why it is very abstract is that the intermediate processing link is a black box operation for developers , Just see the input and output , The author draws the following diagram according to his own understanding , Hope to help you understand css The documents are all over webpack How the packaging process is handled (plugins Some have not been studied , Not involved in the processing chain ).

author : Dashi doesn't talk
link :webpack4.0 Crush one by one (2)—— CSS piece
source : Blog Garden
The copyright belongs to the author . Commercial reprint please contact the author for authorization , Non-commercial reprint please indicate the source .

版权声明
本文为[GZXZSJ]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224172221565k.html

Scroll to Top