A: What is POSTCSS?
POSTCSS is a style processing tool that re-defines CSS through a custom plug-in and tool ecosystem. It encourages developers to write code using the canonical CSS native syntax, and then configures the compiler transformation to require a compatible version of the browser, and finally compiles the source code into the CSS that is available to the target browser.
The difference between it and stylus is that it can flexibly extend its supported features through the plug-in mechanism, unlike the stylus syntax is fixed, it is used very much, such as CSS automatically prefix, using the next generation of CSS syntax and so on.
POSTCSS official has a lot of plug-ins, view plug-ins (https://github.com/postcss/postcss/blob/HEAD/README-cn.md), below we first look at Postcss in Webpack build configuration, And the use of common plug-ins are respectively spoken.
II: Use POSTCSS in Webpack
For example, we use stylus to write CSS code, so the file is such a file name. styl, so the file needs to go through Stylus-loader, Postcss-loader Css-loader, Style-loader compile. Therefore, the following configuration is required:
{ /\.styl$/, use : [ { ' style-loader ', options: {} }, { ' Css-loader ', options: {} }, { ' postcss-loader ', options: {} } , { ' stylus-loader ', options: {} } ]}
As above configuration, so we want to configure the compiler on Webpack as above, so we need to install as above compiler: the following command:
After the installation is complete, we will add the POSTCSS configuration in Webpack, the code is as follows:
Module.exports = { module: { rules: [ { // use regular to match test:/\.styl$/ , use:ExtractTextPlugin.extract ({use : [ { ' style-loader ', options: {} } {' Css-loader ', Options: {}}, {' Postcss-loader ', Options: {} }, { ' stylus-loader ', options: {} } ]}} }}}
Before packing, let's look at the entire directory structure of our project as follows:
# # # directory structure as follows: Demo1 # project Name| |---Dist # directory files generated after packaging| |---Node_modules # all dependent packages| |---JS # Store all JS files| | |--Demo1.js| | |--main.js # JS Portal file| || |---webpack.config.js # webpack config file| |---index.html # HTML file| |---Styles # Store all CSS style files| | |--main.styl # main.styl file| | |--Index.styl| |---. Gitignore| |---readme.md| |---Package.json| |---. BABELRC # Babel transcoding file
The Styles/main.styl code is as follows:
@import "./index.styl"; #app font-size 18px width 200px height 200px display Flex
The Styles/index.styl code is as follows:
Body font-size 12px
The Js/main.js code is as follows:
Import '.. /styles/main.styl ';
Then run the package command NPM run Dev and report the following error:
So in addition to installing stylus-loader, we also need to install the stylus package, the following installation command:
NPM Install Stylus--save-dev
After installation, we ran NPM run Dev, and the error was sent, as follows:
Hint No postcss Config found such errors, through Baidu Search, it is said in the project root directory, create a new Postcss.config.js file, and then add a simple code as follows:
Module.exports = {};
Then we ran NPM Run Dev, and then we sent the following error: as shown:
Then continue to search the answer, found that configuration styl file configuration seems to be problematic, you need to configure the following:
module.exports = // using regular to match test:/\.styl$/, use: Extracttextplugin.extract ({fallback: {loader: ' style-loader ' , options: {}}, {loader: ' stylus-loader '
Then continue running the code without an error. But as the above code only configures the POSTCSS, but does not use the internal plug-in, so we need to add some of the corresponding common plug-ins, such as autoprefixer automatically added prefix, Cssnano compression CSS code, postcss-cssnext the next generation of CSS , using CSS4 's new syntax, and so on.
Now install these plug-ins first, such as the following command installation:
NPM Install--save-dev autoprefixer Cssnano postcss-cssnext
Now the Webpack configuration should read as follows:
Module.exports ={module: {rules: [{//use regular to matchTest:/\.styl$/, Use:ExtractTextPlugin.extract ({fallback: {loader:' Style-loader '}, use: [{loader:' Css-loader ', Options: {}}, {loader:' Postcss-loader ', Options: {ident:' Postcss ', plugins: [Require (' Autoprefixer ') (), Require (' Postcss-cssnext ') (), Require (' Cssnano ') ()]}}, {loader:' Stylus-loader ', Options: {}}]})}}}
After the configuration is complete, we continue to package with NPM run Dev, and you can see the following prompt:
Hint Postcss-cssnext already contains the function of Autoprefixer plug-in, so webpack need to remove autoprefixer. So we continue to pack and run: as shown:
Look at the MAIN.CSS code on the page as follows:
This means that postcss adds a compatibility prefix through plug-in support, and can use CSS syntax that has not yet been supported by the browser, such as variables, calc (), and so on. Note here that the Autoprefixer plugin is not used when using Postcss-cssnext because Postcss-cssnext contains the Autoprefixer plugin.
Three: Postcss-pxtorem plug-in converts PX into REM
1. To use the plugin, you need to install it first, such as the following command:
NPM Install--save-dev Postcss-pxtorem
2. Integration of Postcss-pxtorem in Webpack, the following code configuration:
Module.exports ={module: {rules: [{//use regular to matchTest:/\.styl$/, Use:ExtractTextPlugin.extract ({fallback: {loader:' Style-loader '}, use: [{loader:' Css-loader ', Options: {}}, {loader:' Postcss-loader ', Options: {ident:' Postcss ', plugins: [Require (' Postcss-cssnext ') (), Require (' Cssnano ') (), Require (' Postcss-pxtorem ') ({rootvalue:100, Propwhitelist: []})]}}, { Loader:' Stylus-loader ', Options: {}}]})}}}
Once you have configured Postcss-pxtorem on the code, and then run NPM run Dev, you can see that the code px has been converted to REM as shown.
As above by using PX to write code can be converted to REM, but sometimes we do not want to convert, such as 1px border and so on, I would like to use PX to express, then we can write PX or px to solve, the following code is shown:
The specific configuration of the Postcss-pxtorem is as follows:
Require (' Postcss-pxtorem ') ({ 5, proplist: [' * '], Selectorblacklist: [], true, false, .)
Suppose the design manuscript is 750 wide;
Rootvalue is 75, which says the root element size is set.
Unitprecision is 5, which is the number of decimal places retained after conversion to REM.
Selectorblacklist is an array of filters for the CSS selector, such as you set to [' FS '], that is, for example, the FS-XL class name, where the PX style will not be converted,
The regular notation is also supported here.
Minpixelvalue option, I set 12, meaning that all styles less than 12px are not converted.
Proplist is a list of properties that will be converted, set to [' * '] all, assuming you need to set only the border, write [' * ', '!border* '] meaning to exclude attributes with border.
Four: merger of Postcss-sprites Sprite Chart
1. The installation command is as follows:
NPM Install--save-dev postcss-sprites
2. The Webpack configuration is as follows:
Module.exports ={module: {rules: [{//use regular to matchTest:/\.styl$/, Use:ExtractTextPlugin.extract ({fallback: {loader:' Style-loader '}, use: [{loader:' Css-loader ', Options: {}}, {loader:' Postcss-loader ', Options: {ident:' Postcss ', plugins: [Require (' Postcss-cssnext ') (), Require (' Cssnano ') (), Require (' Postcss-pxtorem ') ({rootvalue:100, Propwhitelist: []}), Require (' Postcss-sprites ') ()]}}, {loader:' Stylus-loader ', Options: {}}]})}}}
As on the Postcss-sprites code, we will test the code, the following Main.styl code is as follows:
@import "./index.styl"; #app font-size 18px width 200px height 200px display Flex border 1PX solid #ccc . Test1 Width 50% height 400px background url ('.. /images/0001.png ') no-repeat 0 0.test2 width 50% height 200px margin-top 20px background url (' ... /images/0002.png ') no-repeat 0 0
Then after we pack the files, the main.css becomes as follows:
Postcss All Plugin view (HTTPS://GITHUB.COM/POSTCSS/POSTCSS/BLOB/HEAD/README-CN.MD), can be packaged in the project according to your own needs.
Here are all the webpack.config.js codes below:
Const PATH = require (' path ');//plugin for extracting CSSConst Extracttextplugin = require (' Extract-text-webpack-plugin '); Const Clearwebpackplugin= Require (' Clean-webpack-plugin '); Module.exports={entry:'./js/main.js ', Output: {filename:' Bundle.js ', //Place the output files in the Dist directoryPath:path.resolve (__dirname, ' dist ')), Publicpath:'/dist '}, Mode:' Development ', module: {rules: [{//use regular to matchTest:/\.styl$/, Use:ExtractTextPlugin.extract ({fallback: {loader:' Style-loader '}, use: [{loader:' Css-loader ', Options: {}}, {loader:' Postcss-loader ', Options: {ident:' Postcss ', plugins: [Require (' Postcss-cssnext ') (), Require (' Cssnano ') (), Require (' Postcss-pxtorem ') ({rootvalue:100, Unitprecision:5, Propwhitelist: []}), Require (' Postcss-sprites ') ()]}}, {loader:' Stylus-loader '( options: {}}]})}, {test:/\. (png|jpg) $/, Loader:' Url-loader ', Options: {limit:10000, Name:' [name]. [ext] '}}, {test:/\.js$/, exclude:/(Node_modules)/,//Exclude FilesLoader: ' Babel-loader '}]}, resolve: {//modules: [' plugin ', ' JS ']}, Externals: {jquery:' JQuery '}, Devtool:' Source-map ', Devserver: {//ContentBase:path.join (__dirname, "Dist"),port:8081, Host:' 0.0.0.0 ', headers: {' X-foo ': ' 112233 ' }, //Hot:true,Inlinetrue, //Open:true,Overlaytrue, stats:' Errors-only '}, plugins: [//new Clearwebpackplugin ([' Dist ']), NewExtracttextplugin ({//the name of the. css file extracted from the JS filefilename: ' Main.css '}) ]};
The Package.json becomes as follows:
{ "Name": "Demo1", "Version": "1.0.0", "description": "", "Main": "Index.js", "Scripts": { "Dev": "Webpack-dev-server--progress--colors--devtool cheap-module-eval-source-map--hot--inline", "Build": "Webpack--progress--colors--devtool cheap-module-source-map" }, "Author": "", "License": "ISC", "Devdependencies": { "Babel-core": "^6.26.3", "Babel-loader": "^7.1.5", "Babel-plugin-transform-runtime": "^6.23.0", "Babel-preset-env": "^1.7.0", "Babel-preset-stage-2": "^6.24.1", "Clean-webpack-plugin": "^0.1.19", "Css-loader": "^1.0.0", "Cssnano": "^4.0.5", "Extract-text-webpack-plugin": "^4.0.0-beta.0", "File-loader": "^1.1.11", "Path": "^0.12.7", "Postcss-cssnext": "^3.1.0", "Postcss-loader": "^3.0.0", "Postcss-pxtorem": "^4.0.1", "Postcss-sprites": "^4.2.1", "Style-loader": "^0.21.0", "Stylus": "^0.54.5", "Stylus-loader": "^3.0.2", "Uglifyjs-webpack-plugin": "^1.2.7", "Url-loader": "^1.0.1", "Webpack": "^4.16.1", "Webpack-cli": "^3.0.8", "Webpack-dev-server": "^3.1.4" }, "Dependencies": { "Axios": "^0.18.0", "Http-proxy-middleware": "^0.18.0", "jquery": "^3.3.1" }}
Webpack Building Tools---postcss (v)