Web developers love Sass CSS preprocessors. According to Sass's view from the State of CSS survey, every developer understands Sass, 89% of developers use it regularly, and 88% of developers are highly satisfied with it.
Many web packagers include Sass processing, but you may also use PostCSS without knowing it. PostCSS is mainly known for its Autoprefixer plugin, which automatically adds -webkit, -moz, and -ms vendor prefixes to CSS properties when needed. Its plugin system means it can do more... For example, you can compile .scss files without using the Sass compiler.
This tutorial explains how to create a custom CSS preprocessor that compiles Sass syntax and adds more features. It's ideal for anyone who knows some Node.js and has specific CSS needs.Key Points
postcss-scss
, postcss-advanced-variables
and postcss-nested
. autoprefixer
Compile the demo src/scss/main.scss source code to build/css/main.css using the following command:
<code>npm run css:dev</code>
<code>npm run css:watch</code>
Ctrl | Cmd C in the terminal.
These two options also create a source map in build/css/main.css.map that references the original source file in the developer tool.Production-level compressed CSS without source map can be compiled using the following command:
<code>npm run css:build</code>
Should you replace Sass with PostCSS?
The latest version of Dart Sass can be installed globally using Node.js npm package manager:
<code>npm run css:dev</code>
Compile Sass .scss code with the following command:
<code>npm run css:watch</code>
Automatically generate source maps (--no-source-map will close them) or add --watch to automatically compile them when source files change.
The latest version of Sass installation space is less than 5MB.
PostCSS should require less resources, and a basic Sass-style compiler with automatic prefix and compression requires less than 1MB of space. In fact, your node_modules folder will expand to over 60MB and will increase rapidly as more plugins are added. This is mainly about installing other dependencies in npm. Even if PostCSS may not use them, it cannot be considered a lightweight alternative.
However, if you are already using PostCSS for Autoprefixer or other purposes, you may not need Sass.Processing speed
It's very fast.
PostCSS is pure JavaScript, and while the benchmarks will vary, it can be three times slower when compiling the same source code.However, if you are already running PostCSS after Sass, this speed difference will be less noticeable. A two-stage process may be slower than using PostCSS alone, as much of its work involves tokenization of CSS properties.
Custom
You may want to have an option to convert HSLA colors to RGB. Writing custom functions may be possible, but other requirements will be impossible - for example inline SVG as background image.
You may prefer that your team does not use nesting or @extend. Lint rules will help, but they won't prevent Sass from compiling valid .scss files.
PostCSS itself does nothing. Processing features require one or more available plugins. Most plugins perform a single task, so if you don't need nesting, don't add nested plugins. If necessary, you can write your own plug-in using the standard JavaScript module that takes advantage of the capabilities of Node.js.
Install PostCSS
If necessary, use npm init to initialize a new Node.js project. Set up PostCSS by installing the following modules to perform basic .scss parsing using plugins for partial, variable, mix, nest and auto-prefix:
<code>npm run css:build</code>
Note: PostCSS can only be run from JavaScript files, but the postcss-cli module provides a wrapper that can be called from the command line. The postcss-scss module allows PostCSS to read .scss files but does not convert them.
Autoprefixer uses browserslist to determine which vendor prefixes are needed based on the list of browsers you support. The easiest way is to define it as a "browserslist" array in package.json. The following example adds a vendor prefix when any browser has at least 2% of the market share:
<code>npm run css:dev</code>
You will usually have a single root Sass .scss file that imports all required partial/component files. For example:
<code>npm run css:watch</code>
Compilation can be initiated by running npx postcss, followed by input files, --output files, and any required options. For example:
<code>npm run css:build</code>
This command:
Alternatively, you can add --watch to automatically compile when modifying the .scss file.
For longer plugin lists, the command line can quickly become difficult to handle. You can define it as an npm script, but the PostCSS configuration file is a simpler option that offers other possibilities.
PostCSS configuration file is a JavaScript module file named postcss.config.js, usually stored in the root directory of the project (or whatever directory you run PostCSS from). The module must export a single function:
<code>npm install -g sass</code>
It passes a cfg object with properties set by the postcss command. For example:
<code>sass [input.scss] [output.css]</code>
You can check these properties and react accordingly - for example, to determine whether you are running in development mode and whether you are processing the .scss input file:
<code>npm install --save-dev postcss postcss-cli postcss-scss postcss-advanced-variables postcss-nested autoprefixer</code>
The function must return an object whose property name matches the postcss-cli command line option. The following configuration file copies the long quick start command used above:
<code>"browserslist": [ "> 2%" ],</code>
You can now run PostCSS with shorter commands:
<code>// 根Sass文件 // src/scss/main.scss @import '_variables'; @import '_reset'; @import 'components/_card'; // 等。</code>
The following are some things to note:
If you prefer to put postcss.config.js in another directory, you can refer to it with the --config option - for example --config /mycfg/. In the example project, the above configuration is in config/postcss.config.js. It is referenced by running npm run css:basic, which calls:
<code>npm run css:dev</code>
The following section provides some examples of PostCSS plugins that can parse additional .scss syntax or provide processing functionality beyond the scope of the Sass compiler.
Design tokens are a technology-independent way to store variables such as company-wide fonts, colors, spacing, etc. You can store the token name-value pair in a JSON file:
<code>npm run css:watch</code>
Then refer them in any web, Windows, macOS, iOS, Linux, Android, or other applications.
Sass does not directly support design tokens, but JavaScript objects with variables attributes (which hold name-value pairs) can be passed to existing postcss-advanced-variables PostCSS plugin:
<code>npm run css:build</code>
The plugin converts all values into global Sass $ variables that can be used in any part. The fallback value can be set to ensure that the variable is available even if it is missing in the token. For example:
<code>npm install -g sass</code>
The token variable can then be referenced in any .scss file. For example:
<code>sass [input.scss] [output.css]</code>
In the example project, a token.json file is defined, which is loaded and used when running npm run css:dev.
Sass Map is a key-value object. The map-get function can find values by name.
The following example defines a media query breakpoint as a Sass map and uses a response mixin to get the named value:
<code>npm install --save-dev postcss postcss-cli postcss-scss postcss-advanced-variables postcss-nested autoprefixer</code>
The default properties and media query modifications can then be defined in the same selector. For example:
<code>"browserslist": [ "> 2%" ],</code>
Compiled to CSS:
<code>// 根Sass文件 // src/scss/main.scss @import '_variables'; @import '_reset'; @import 'components/_card'; // 等。</code>
postcss-map-get plugin adds Sass map processing. Install it with the following command:
<code>npx postcss ./src/scss/main.scss \ --output ./build/css/main.css \ --env development \ --map \ --verbose \ --parser postcss-scss \ --use postcss-advanced-variables postcss-nested autoprefixer</code>
Then add it to postcss.config.js:
<code>// postcss.config.js module.exports = cfg => { // ... 配置 ... };</code>
Since we have added media queries, it will be useful to combine them and sort them in mobile priorities. For example, the following CSS:
<code>{ cwd: '/home/name/postcss-demo', env: 'development', options: { map: undefined, parser: undefined, syntax: undefined, stringifier: undefined }, file: { dirname: '/home/name/postcss-demo/src/scss', basename: 'main.scss', extname: '.scss' } }</code>
can be merged into:
<code>// postcss.config.js module.exports = cfg => { const dev = cfg.env === 'development', scss = cfg.file.extname === '.scss'; // ... 配置 ... };</code>
This is not possible in Sass, but can be implemented using the PostCSS postcss-sort-media-queries plugin. Install it with the following command:
<code>// postcss.config.js module.exports = cfg => { const dev = cfg.env === 'development', scss = cfg.file.extname === '.scss'; return { map: dev ? { inline: false } : false, parser: scss ? 'postcss-scss' : false, plugins: [ require('postcss-advanced-variables')(), require('postcss-nested')(), require('autoprefixer')() ] }; };</code>
Then add it to postcss.config.js:
<code>npx postcss ./src/scss/main.scss \ --output ./build/css/main.css \ --env development \ --verbose</code>
Asset management is not provided in Sass, but postcss-assets make it easy. The plugin parses the CSS image URL, adds cache clearing, defines the image size, and inlines the file using base64 notation. For example:
<code>npx postcss src/scss/main.scss \ --output build/css/main.css \ --env development \ --verbose \ --config ./config/</code>
Compiled as:
<code>{ "font-size": "16px", "font-main": "Roboto, Oxygen-Sans, Ubuntu, sans-serif", "lineheight": 1.5, "font-code": "Menlo, Consolas, Monaco, monospace", "lineheight-code": 1.2, "color-back": "#f5f5f5", "color-fore": "#444" }</code>
Use the following command to install the plug-in:
<code>// PostCSS配置 module.exports = cfg => { // 将令牌导入为Sass变量 const variables = require('./tokens.json'); // 新的 const dev = cfg.env === 'development', scss = cfg.file.extname === '.scss'; return { map: dev ? { inline: false } : false, parser: scss ? 'postcss-scss' : false, plugins: [ require('postcss-advanced-variables')({ variables }), // 已更新 require('postcss-nested')(), require('autoprefixer')() ] }; };</code>
Then add it to postcss.config.js. In this case, the plugin is instructed to look up images in the src/images/ directory:
<code>// 如果tokens.json中未设置“color-back”值,则将默认背景颜色设置为#FFF $color-back: #fff !default;</code>
cssnano sets the standard for CSS compression. Compression may require more processing time than other plugins and therefore can only be applied in production.
Install cssnano using the following command:
<code>body { font-family: $font-main; font-size: $font-size; line-height: $lineheight; color: $color-fore; background-color: $color-back; }</code>
Then add it to postcss.config.js. In this case, compression will only be performed if NODE_ENV is set to anything other than development:
<code>npm run css:dev</code>
Setting --env to production triggers compression (and removes the source map):
<code>npm run css:watch</code>
In the example project, production CSS can be compiled by running npm run css:build.
PostCSS is a powerful and configurable tool that can compile .scss files and enhance (or limit) the standard Sass language. If you are already using PostCSS for Autoprefixer, you can completely remove the Sass compiler while retaining your favorite syntax.
More links:
What is PostCSS? PostCSS is a tool for converting styles using JavaScript plugin. It is commonly used in web development and uses various plugins to handle CSS to enhance and extend the functionality of standard CSS.
How is PostCSS different from traditional CSS preprocessors like Sass or Less? Unlike traditional preprocessors, PostCSS itself is not a preprocessor, but a tool that uses plug-ins to convert CSS. It allows developers to use modular and customizable methods by selecting only the plugins needed for a specific project.
What are some common use cases for PostCSS? PostCSS is usually used for tasks such as automatic prefix, code checking, compression, variable replacement, and future CSS syntax compatibility. It provides a flexible and modular system for enhancing the functionality of standard CSS.
How to install and set up PostCSS for my project? You can use npm (Node Package Manager) to install PostCSS and its plugins. After installation, you need to create a configuration file (usually called postcss.config.js) to define the plugin for the project and its settings.
What is an automatic prefix and why is it useful in PostCSS? Automatic prefix is a process where PostCSS automatically adds vendor prefixes to CSS properties to ensure compatibility with different browsers. This helps developers write cleaner code, avoiding manual vendor-specific prefixes.
Can I use PostCSS with preprocessors like Sass or Less? Yes, PostCSS can be used with preprocessors like Sass or Less. You can take advantage of both by further processing the output of the preprocessor by using the PostCSS plugin.
The above is the detailed content of How to Use PostCSS as a Configurable Alternative to Sass. For more information, please follow other related articles on the PHP Chinese website!