• Author: Chen Da Yu Tou
  • Making: KRISACHAN

What is postcss

According to the website, it is A tool for transforming CSS with JavaScript.

Similarly, CSS preprocessors such as Sass, Less, and Stylus provide an easier way to write CSS.

While postCSS allows you to write variables, functions, mixed macros, extensions, conditional statements, loops, and other syntax that CSS does not support (or support) well, postCSS is essentially a business-neutral CSS tool. Many of these functions rely on plugins in the community.

It works just like Babel in JS.

What can Postcss do

Improve code readability

Add vendor-specific prefixes to CSS rules using data retrieved from the Can I Use web site. Autoprefixer automatically gets the browser’s popularity and supported attributes, and automatically prefixes CSS rules based on this data.

The following is an example:

/ / input:fullscreen-webkit-fullscreen {} :-ms-fullscreen {}:fullscreen{}Copy the code

Bring the CSS features of the future to today!

The PostCSS Env helps you turn the latest CSS syntax into a syntax that most browsers understand and determines polyfills you need according to your target browser or runtime environment. This is implemented based on CSSDB.

The following is an example:

/ / inputbody {
  color: lch(53 105 40); } / / outputbody {
  color: rgb(250.0.4);
}
Copy the code

Ending the Global CSS

CSS modules allow you to never worry about generic names causing conflicts, just use the names that make the most sense.

The following is an example:

/ / input.name {
  color: gray; } / / output.Logo__name__SVK0g {
  color: gray;
}
Copy the code

Avoid errors in CSS code

Enforce consistency constraints and avoid errors in style sheets by using stylelint. Stylelint is a modern CSS code checker. It supports the latest CSS syntax, as well as CSS-like syntax such as SCSS.

The following is an example:

// Enter a {color: #d3; } // Console output app.css 2:10 Invalid hex colorCopy the code

How to use postcss

We can use WebPack as an example to see how to configure this.

The first step is to install the basic plug-in:

npm install postcss-loader postcss --save-dev
or
yarn add postcss-loader postcss -D
Copy the code

Then add to your webpack.config.js:

module.exports = {
  module: {
    rules: [{test: /\.css$/,
        use: ["style-loader"."css-loader"."postcss-loader"}]}};Copy the code

Then create the file postcss.config.js in the root directory as follows:

module.exports = {
  plugins: []};Copy the code

Now let’s add plug-ins for the four features mentioned in What you can do with PostCSS.

Plug-ins corresponding to the four features are as follows:

Autoprefixer (improve code readability)

Installation method:

npm install autoprefixer --save-dev
or
yarn add autoprefixer -D
Copy the code

The configuration is as follows:

// postcss.config.js
const autoprefixer = require("autoprefixer");
module.exports = {
  plugins: [autoprefixer]
};
Copy the code

Autoprefixer is associated with Browserslist, which is a tool that tells the browser and Node platform where the packaging tool project will run to create compatibility code.

So we can add the browserslist property to package.json, or the.browserslistrc file to the root directory, as shown in the following example (the rules can be configured depending on the project) :

last 2 version
> 1%
IE 11
Copy the code

Browserslist’s data comes from Can I Use.

We can check for statement matches with browserslist.dev. Screenshot below:

So we have:

// input
.example {
  display: grid;
  transition: all 0.5 s;
  user-select: none;
  background: linear-gradient(to bottom, white, black);
}

// output
/ * * Prefixed by https://autoprefixer.github.io * PostCSS: v7.0.29, * Autoprefixer: v9.7.6 * Browsers: last 2 version * /
.example {
  display: -ms-grid;
  display: grid;
  -webkit-transition: all 0.5 s;
  transition: all 0.5 s;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  background: -webkit-gradient(
    linear,
    left top,
    left bottom,
    from(white),
    to(black)
  );
  background: linear-gradient(to bottom, white, black);
}
Copy the code

We can see the results online at autoprefixer.github. IO /

Postcss-preset -env (Bring future CSS features to today!)

Installation method:

npm install postcss-preset-env --save-dev
or
yarn add postcss-preset-env -D
Copy the code

The configuration is as follows:

// postcss.config.js
const postcssPresetEnv = require("postcss-preset-env");
module.exports = {
  plugins: [postcssPresetEnv(/* pluginOptions */)]};Copy the code

Postcss-preset -env allows us to use CSS attributes that are unpopular or unsupported in browsers.

The following is an example:

// input
:root {
  --fontSize: 1rem;
  --mainColor: rgba(18.52.86.0.47059);
  --secondaryColor: rgba(102.51.153.0.9);
}

@media (max-width: 50rem) {
  body {
    color: var(--mainColor);
    font-family: system-ui;
    font-size: var(--fontSize);
    line-height: calc(var(--fontSize) * 1.5);
    overflow-wrap: break-word;
    padding-left: calc(var(--fontSize) / 2 + 1px);
    padding-right: calc(var(--fontSize) / 2 + 1px);
  }
}

// output Stage 0 > 3%
:root {
  --fontSize: 1rem;
  --mainColor: rgba(18.52.86.0.47059);
  --secondaryColor: rgba(102.51.153.0.9);
}

html {
  overflow-x: hidden;
  overflow-y: auto;
  overflow: hidden auto;
}

@media (max-width: 50rem) {
  body {
    color: var(--mainColor);
    font-family: system-ui;
    font-size: var(--fontSize);
    line-height: calc(var(--fontSize) * 1.5);
    overflow-wrap: break-word;
    padding-left: calc(var(--fontSize) / 2 + 1px);
    padding-right: calc(var(--fontSize) / 2 + 1px); }}Copy the code

We can use csstools. Making. IO/postcss – pre… Watch the compilation effect online.

There are seven options: Stage, Features, Browsers, insertBefore, insertAfter, autoprefixer, Preserve, and importFrom.

For details and examples, see github.com/csstools/po… .

Two options are highlighted here:

stage

Before we talk about stage, we need to know the concept of CSSDB.

CSSDB is the implementation baseline of postCSS-preset – Env, which is the new CSS features and the process in which these features are proposed to become a standard.

CSSDB, like ECMA, has different processes for new attributes. The specific processes are as follows:

Stage 0: Brain storm. Highly unstable and subject to change.

Stage 1: Experiment. It is also very volatile and subject to change, but the proposal has been endorsed by W3C members.

Stage 2: Recognition. Highly unstable and subject to change, but under active investigation.

Stage3: Hug phase. Stable and not changing much, this feature may become standard.

Stage4: Standard stage. The final solution, supported by all major browsers.

So the stage configuration options are 1, 2, 3, and 4.

features

The Features option enables or disables specific polyfills by ID. Enable is true.

Please refer to github.com/csstools/po…

Css-modules (Terminating global CSS)

Installation method:

npm install postcss-modules --save-dev
or
yarn add postcss-modules -D
Copy the code

The configuration is as follows:

// postcss.config.js
const postcssModules = require("postcss-modules");
module.exports = {
  plugins: [postcssModules(/* pluginOptions */)]};Copy the code

Css-modules allows us to write code in modular form. The following is an example:

// input
.grid {
  display: grid;
  grid: repeat(2.240px) / auto-flow 320px;
  & > div {
    background-color: #8ca0ff;
    width: 200px;
    height: 200px;
    transition: 1s;
  }
}

// output
.demo__grid___2lKm5 {
  display: -ms-grid;
  display: grid;
  grid: repeat(2.32vw) / auto-flow 42.667 vw;
}
.demo__grid___2lKm5 > div {
  background-color: #8ca0ff;
  width: 26.667 vw;
  height: 26.667 vw;
  -webkit-transition: 1s;
  transition: 1s;
}
Copy the code

In fact, if you do not use postCSs-modules, you can also use CSS-loader to enable CSS modularization. The specific configuration is as follows:

// webpack.config.js
module.exports = {
  module: {
    rules: [{test: /\.css$/i,
        use: [
          {
            loader: "css-loader".options: {
              modules: true.importLoaders: true.localIdentName: "[name]__[local]___[hash:base64:5]"}}]}};Copy the code

Stylelint (to avoid errors in CSS code)

Just as we can use ESLint for code checking in JS, we can also use stylelint for code checking in CSS.

Installation method:

npm install stylelint stylelint-config-standard --save-dev
or
yarn add stylelint stylelint-config-standard -D
Copy the code

The configuration is as follows:

// webpack.config.js
const StyleLintPlugin = require("stylelint-webpack-plugin");

module.exports = {
  plugins: [new StyleLintPlugin /* pluginOptions */()]};Copy the code

Then create a.stylelintrc or stylelint.config.js file in the root directory (the file can be configured in StyleLintPlugin) with the following contents:

{
    "extends": "stylelint-config-standard",
    "rules": {/* pluginOptions */}
}
Copy the code

So when our code is not standard, we can see an error like this on the command line:

You can also find the corresponding stylelint plug-in in the editor for automatic CSS code formatting.

ying-template

Ying-template is a multi-page scaffolding based on WebPack5 + typeScript4 + Postcss8. In the first version, sass, less, However, because postCSS smells too good, they removed sass and less, leaving only PostCSS.

Ying-template is currently in production under a proprietary project owned by Fishhead’s original owner, and is also in use with Another open-source library, Ying-Data Structures-Algorithms. In addition, there are some partners in the community to use or reference in the project, you can also clone down to have a look, you can feel how attractive CSS in postCSS is.

It is also worth mentioning that, in addition to the basic plugins described above, there are many interesting plugins available in the PostCSS community. You can choose the plugins you want to use at www.postcss.parts/.

The resources

  1. ying-template
  2. PostCSS
  3. The future of CSS is here
  4. Autoprefixer
  5. Autoprefixer CSS online
  6. browserslist
  7. PostCSS Preset Env
  8. postcss.parts