Webpack combat (VII): Simple usage and get to know some of the usage of plug-ins PostCSS

Unwittingly Spring Festival is coming up, today is a holiday the next day, then go home to think about all the time is not their own, and to play with their children, relatives and so on, I took advantage of the two in Zhengzhou day, a few days after the Spring Festival to publish a full article to advance. In advance I wish you all a Happy New Year! !

As I have written six relevant technical knowledge Webpack aspects, today I share the main technical aspects related to PostCSS, PostCSS strictly speaking not a css preprocessor, but a conversion tool CSS code with JavaScript and plug-ins tool. Its mode of operation is to receive the source code and the style referred to compile plug-in processing, the final output CSS. By many powerful plug-PostCSS included, it allows us to use the updated CSS properties to ensure better browser compatibility.

PostCSS Features

  1. Support future css, css future use cssnext writing
  2. Compilation speed has been greatly improved
  3. Rich plug-in system
  4. css can be modularly

PostCSS usage of Webpack

Use npm install postcss-loader, postcss-loader and is connected PostCSS Webpack. Installation command line as follows:

npm install postcss-loader --save-dev

webpack.config.js configuration is as follows:

const path = require('path')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
  context: path.join(__dirname, './src'),
  entry: {
    index: './index.js'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].js'
  },
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [{
          loader: MiniCssExtractPlugin.loader,
          options: {
            publicPath: './dist'
          },
        }, 'css-loader'], // "css-loader" 将 CSS 转化成 CommonJS 模块
        exclude: /node_modules/
      },
      {
        test: /\.scss$/i,
        use: ['style-loader',
        {
          loader: 'css-loader',
          options: {
            sourceMap: true
          }
        },
        {
          loader: 'sass-loader',
          options: {
            sourceMap: true
          }
        },
        'postcss-loader'  //配置postcss-loader
        ], 
        exclude: /node_modules/
      },
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            cacheDirectory: true,
            presets: [
              [
                'env', {
                  modules: false
                }
              ]
            ]
          }
        }
      }
    ],
  },
  plugins: [new MiniCssExtractPlugin({
    filename: '[name].css',
    chunkFilename: '[id].css'
  })],
}

postcss-loader can combine css-loader, can also be used alone, it is used alone can achieve the desired effect, but when used alone is not recommended for use @import in css syntax, or will cause redundant code. The official recommendation is to use a combination of both, do not use alone.

postcss and Autoprefixer

postCSS must have a separate configuration file, so you need to configure a postcss.config.js in the project root directory,
this can be combined with the plug-ins automatically add a prefix Autoprefixer use, Autoprefixer browser automatically obtain popularity and support of properties, Based on these data and help you to automatically add a prefix to a CSS rule. This is the most widely postCss a scenario. First mounting Autoprefixer, install command code is as follows:

npm install autoprefixer  --save-dev

In postcss.config.js added autoprefixer, the configuration code is as follows:

const autoprefixer = require('autoprefixer')
module.exports = {
  parser: 'sugarss',
  plugins: {
    'autoprefixer': {
      flex: true,
      browsers: [
        '> 1%',
        'last 3 versions',
        'android 4.2',
        'ie 8'
      ]
    }
  }
}

We can add features need to be supported (such as grid) and which browser (browsers) compatible autoprefixer in. Once configured, we can use some of the newer CSS features. Such as:

.main{
dislay: grid;
}

Due to the development of grid configuration is true, that is, grid characteristics add the prefix ie, after compiling become:

.main{
display: -ms-grid;
dislay: grid;
}

postcss and cssnext

postcss be used in conjunction with cssnext, so you can use the syntax of CSS properties latest in the application.
Home npm use command-line installation:

npm install postcss-cssnext --save-dev

Was then added in the appropriate configuration posts.config.js code is as follows:

const postcssCssnext = require('postcss-cssnext')
module.exports = {
  parser: 'sugarss',
  plugins: {
    'postcssCssnext': {

      browsers: [
        '> 1%',
        'last 2 versions'
      ]
    }
  }
}

After you specify that you need a supported browser, we can smoothly use of the characteristics of CSSNext. PostCSS will help us to translate CSSNext syntax for the browser to accept the properties and forms. For example the following code:

/** main.css **/
:root {
	--highligtColor: hwb(190, 35%, 20%);
}
body {
	color: var(--highlightColor)
}

Package compiled results are as follows:

body {
	color: rgb(89, 185, 204)
}

postcss and stylelint

stylelint is a tool css code quality testing, we can add a variety of its rules to the Uniform Code style project, to ensure high code quality.
Home first with command-line installation stylelint code is as follows:

npm install stylelint --save-dev

postcss.config.js configuration code is as follows:

const stylelint = require('stylelint')
module.exports = {
  plugins: {
    'stylelint': {
      config: {
        rules: {
          'declaration-no-important': true
        }
      }
    }
  }
}

Here we add a rule declaration-no-important, when our code appears in the "! Important" will give warning. For example the following code:

/** a.scss**/
$base-color: red;

html {
  body{
    color: $base-color !important;
  }
}

Packing results as shown:
Here Insert Picture Description
it can be seen warning.
Use stylelint can detect problem patterns (syntax errors, duplicate attributes, etc.) in the code, to help us write more secure and more consistent style code.

CSS Modules

CSS Modules Modular Terminator css is global, that you never have to worry about naming conflicts caused by too popular, as long as the most significant names on the list.
css Modularity is more popular in recent years, a development model that allows developers css like other languages, has its own module scope, let css also have modular features:

  • Each CSS style file has a separate scope, naming conflicts will not occur and the outside world.
  • Dependency management of CSS, CSS file can be introduced by a relative path.
  • CSS modules can be reused by other composes easily.

Use CSS Modules need not install other components, you only need to configure the css-loader.
Configuration web pack.config.js configured as follows:

const path = require('path')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
  context: path.join(__dirname, './src'),
  entry: {
    index: './index.js'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].js'
  },
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ['style-loader', {
          loader: 'css-loader',
          options: {
            modules: {
              localIdentName: '[path][name]__[local]--[hash:base64:5]',
            }
          }
        }]
      },
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            cacheDirectory: true,
            presets: [
              [
                'env', {
                  modules: false
                }
              ]
            ]
          }
        }
      }
    ],
  }
}

We only need to configure modules.localIdentName configuration can be

  • [Name] refers to the module name is replaced here style.
  • [Local] refer to the original choice identifier, here it is replaced title.
  • [hash: base64: 5] refers to a 5-bit hash value, the hash value is calculated based on the module name and the identifier, the identifier of the different modules in the same pattern does not cause a conflict.
    cs s code is as follows:
/** style.css**/
.tit {
  color: #ff0000;
}
// index.js
import style from  './style.css';
document.write(`<p class="${style.tit}">hello webpack2</p>`);

After the code is compiled into a class to find .style__tit-Vp6X7, before I introduced in the js css files, the introduction of direct import, do not need to define a name, but this css css modules introduced when the need to define an object, and then reference, the final HTML CSS class to the class name matches compiled with us on.
Operating results as shown:
Here Insert Picture Description

to sum up:

Share with you today is mainly related postcss, including the postcss used in conjunction with webpack, autoprefixer automatically add a prefix, stylelint detection code, css modules and so on. This is just a personal point of view, if there are deficiencies, also please advise. If you want to know more, please scan the following QR code:
Here Insert Picture Description

Published 248 original articles · won praise 130 · views 440 000 +

Guess you like

Origin blog.csdn.net/yilanyoumeng3/article/details/104058674