Home > Web Front-end > CSS Tutorial > How to Use PostCSS as a Configurable Alternative to Sass

How to Use PostCSS as a Configurable Alternative to Sass

Lisa Kudrow
Release: 2025-02-12 08:24:12
Original
898 people have browsed it

How to Use PostCSS as a Configurable Alternative to Sass

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

    Configurability and Customization: PostCSS provides a highly configurable environment compared to Sass. It runs based on the plug-in architecture, each plug-in performs specific tasks, allowing developers to customize their settings according to specific project needs.
  • Performance Notes: While the Dart-based Sass compiler is fast, PostCSS built on JavaScript may be slower. However, for projects that already use PostCSS, the speed difference may be negligible, making it a viable single-process solution.
  • Install and Setup: PostCSS can be integrated with various build tools or run from the command line. The basic settings for a Sass-like environment require the installation of several plug-ins, such as
  • , postcss-scss, postcss-advanced-variables and postcss-nested. autoprefixer
  • Use plug-ins to enhance functionality: PostCSS goes beyond traditional preprocessor functions, and its plug-ins can handle design tokens, optimize media queries, manage assets, and even perform CSS compression conditionally based on the environment.
  • Potential to simplify the development stack: For teams already using PostCSS, it may be possible to completely eliminate Sass in the development stack and rely on PostCSS to meet all CSS processing needs, including handling Sass-like syntax and features.
Quick Start

A PostCSS sample project can be cloned from GitHub. It requires Node.js, so run npm install to get all dependencies.

Compile the demo src/scss/main.scss source code to build/css/main.css using the following command:

<code>npm run css:dev</code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Use the following command to automatically compile when the file changes:

<code>npm run css:watch</code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
and then exit monitoring by pressing

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>
Copy after login
Copy after login
Copy after login
Copy after login
For more information, see the README.md file.

Should you replace Sass with PostCSS?

The Sass compiler has no problems, but please consider the following factors.

Module dependencies

The latest version of Dart Sass can be installed globally using Node.js npm package manager:

<code>npm run css:dev</code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Compile Sass .scss code with the following command:

<code>npm run css:watch</code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

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

The slow Ruby-based Sass compiler has long disappeared, and the latest version uses the compiled Dart runtime.

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

Sass language contains a large number of functions, including variables, nesting, parts, mixing, etc. But there are some disadvantages:

  1. You can't easily add new features.

    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.

  2. You can't easily limit the feature set.

    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 is easier to configure.

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

PostCSS can be used with webpack, Parcel, Gulp.js, and other build tools, but this tutorial demonstrates how to run it from the command line.

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>
Copy after login
Copy after login
Copy after login
Copy after login
Like the sample project, PostCSS and its plugins are installed locally. This is a practical option if your project may have different compilation requirements.

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 configuration

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>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Your first build

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>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

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>
Copy after login
Copy after login
Copy after login
Copy after login

This command:

  1. Analysis./src/scss/main.scss
  2. Output to ./build/css/main.css
  3. Set NODE_ENV environment variable to development
  4. Output external source map file
  5. Set detailed output and error message
  6. Set the postcss-scss Sass parser, and
  7. Use plugins postcss-advanced-variables, postcss-nested and autoprefixer to handle parts, variables, mixing, nesting and autoprefixer

Alternatively, you can add --watch to automatically compile when modifying the .scss file.

Create PostCSS configuration 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>
Copy after login
Copy after login

It passes a cfg object with properties set by the postcss command. For example:

<code>sass [input.scss] [output.css]</code>
Copy after login
Copy after login

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>
Copy after login
Copy after login

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>
Copy after login
Copy after login

You can now run PostCSS with shorter commands:

<code>// 根Sass文件
// src/scss/main.scss
@import '_variables';
@import '_reset';
@import 'components/_card';
// 等。</code>
Copy after login
Copy after login

The following are some things to note:

  • --verbose is optional: it is not set in postcss.config.js.
  • Sass syntax parsing will be applied only when the input is a .scss file. Otherwise, it defaults to standard CSS.
  • The source map will be output only when --env is set to development.
  • You can still add --watch for automatic compilation.

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>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Add more plugins

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.

Using Design Token

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>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

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>
Copy after login
Copy after login
Copy after login
Copy after login

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>
Copy after login
Copy after login

The token variable can then be referenced in any .scss file. For example:

<code>sass [input.scss] [output.css]</code>
Copy after login
Copy after login

In the example project, a token.json file is defined, which is loaded and used when running npm run css:dev.

Add Sass Map support

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>
Copy after login
Copy after login

The default properties and media query modifications can then be defined in the same selector. For example:

<code>"browserslist": [
  "> 2%"
],</code>
Copy after login
Copy after login

Compiled to CSS:

<code>// 根Sass文件
// src/scss/main.scss
@import '_variables';
@import '_reset';
@import 'components/_card';
// 等。</code>
Copy after login
Copy after login

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>
Copy after login

Then add it to postcss.config.js:

<code>// postcss.config.js
module.exports = cfg => {

  // ... 配置 ...

};</code>
Copy after login

Add media query optimization

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>
Copy after login

can be merged into:

<code>// postcss.config.js
module.exports = cfg => {

  const
    dev = cfg.env === 'development',
    scss = cfg.file.extname === '.scss';

  // ... 配置 ...

};</code>
Copy after login

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>
Copy after login

Then add it to postcss.config.js:

<code>npx postcss ./src/scss/main.scss \
    --output ./build/css/main.css \
    --env development \
    --verbose</code>
Copy after login

Add Asset Processing

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

Add compression

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>
Copy after login

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>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Setting --env to production triggers compression (and removes the source map):

<code>npm run css:watch</code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

In the example project, production CSS can be compiled by running npm run css:build.

Migrate to PostCSS?

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:

  • Sass Language Reference
  • PostCSS Home Page
  • PostCSS plugin list
  • Searchable directory for PostCSS plug-in
  • PostCSS plugin on npmjs.com
  • Writing PostCSS plugin
  • PostCSS CLI

Frequently Asked Questions about PostCSS

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template