Transforming styles with JS plugins

  • By PostCSS
  • Last update: Jan 4, 2023
  • Comments: 16

PostCSS Gitter

Philosopher’s stone, logo of PostCSS

PostCSS is a tool for transforming styles with JS plugins. These plugins can lint your CSS, support variables and mixins, transpile future CSS syntax, inline images, and more.

PostCSS is used by industry leaders including Wikipedia, Twitter, Alibaba, and JetBrains. The Autoprefixer PostCSS plugin is one of the most popular CSS processors.

PostCSS takes a CSS file and provides an API to analyze and modify its rules (by transforming them into an Abstract Syntax Tree). This API can then be used by plugins to do a lot of useful things, e.g., to find errors automatically, or to insert vendor prefixes.

Support / Discussion: Gitter
Twitter account: @postcss
VK.com page: postcss
中文翻译: docs/README-cn.md

For PostCSS commercial support (consulting, improving the front-end culture of your company, PostCSS plugins), contact Evil Martians at [email protected].

Sponsored by Evil Martians

Sponsorship

PostCSS needs your support. We are accepting donations at Open Collective.

Sponsored by Tailwind CSS        Sponsored by ThemeIsle

Plugins

Currently, PostCSS has more than 200 plugins. You can find all of the plugins in the plugins list or in the searchable catalog. Below is a list of our favorite plugins — the best demonstrations of what can be built on top of PostCSS.

If you have any new ideas, PostCSS plugin development is really easy.

Solve Global CSS Problem

  • postcss-use allows you to explicitly set PostCSS plugins within CSS and execute them only for the current file.
  • postcss-modules and react-css-modules automatically isolate selectors within components.
  • postcss-autoreset is an alternative to using a global reset that is better for isolatable components.
  • postcss-initial adds all: initial support, which resets all inherited styles.
  • cq-prolyfill adds container query support, allowing styles that respond to the width of the parent.

Use Future CSS, Today

Better CSS Readability

Images and Fonts

Linters

  • stylelint is a modular stylesheet linter.
  • stylefmt is a tool that automatically formats CSS according stylelint rules.
  • doiuse lints CSS for browser support, using data from Can I Use.
  • colorguard helps you maintain a consistent color palette.

Other

  • postcss-rtl combines both-directional (left-to-right and right-to-left) styles in one CSS file.
  • cssnano is a modular CSS minifier.
  • lost is a feature-rich calc() grid system.
  • rtlcss mirrors styles for right-to-left locales.

Syntaxes

PostCSS can transform styles in any syntax, not just CSS. If there is not yet support for your favorite syntax, you can write a parser and/or stringifier to extend PostCSS.

  • sugarss is a indent-based syntax like Sass or Stylus.
  • postcss-syntax switch syntax automatically by file extensions.
  • postcss-html parsing styles in <style> tags of HTML-like files.
  • postcss-markdown parsing styles in code blocks of Markdown files.
  • postcss-jsx parsing CSS in template / object literals of source files.
  • postcss-styled parsing CSS in template literals of source files.
  • postcss-scss allows you to work with SCSS (but does not compile SCSS to CSS).
  • postcss-sass allows you to work with Sass (but does not compile Sass to CSS).
  • postcss-less allows you to work with Less (but does not compile LESS to CSS).
  • postcss-less-engine allows you to work with Less (and DOES compile LESS to CSS using true Less.js evaluation).
  • postcss-js allows you to write styles in JS or transform React Inline Styles, Radium or JSS.
  • postcss-safe-parser finds and fixes CSS syntax errors.
  • midas converts a CSS string to highlighted HTML.

Articles

More articles and videos you can find on awesome-postcss list.

Books

Usage

You can start using PostCSS in just two steps:

  1. Find and add PostCSS extensions for your build tool.
  2. Select plugins and add them to your PostCSS process.

CSS-in-JS

The best way to use PostCSS with CSS-in-JS is astroturf. Add its loader to your webpack.config.js:

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'postcss-loader'],
      },
      {
        test: /\.jsx?$/,
        use: ['babel-loader', 'astroturf/loader'],
      }
    ]
  }
}

Then create postcss.config.js:

module.exports = {
  plugins: [
    require('autoprefixer'),
    require('postcss-nested')
  ]
}

Parcel

Parcel has built-in PostCSS support. It already uses Autoprefixer and cssnano. If you want to change plugins, create postcss.config.js in project’s root:

module.exports = {
  plugins: [
    require('autoprefixer'),
    require('postcss-nested')
  ]
}

Parcel will even automatically install these plugins for you.

Please, be aware of the several issues in Version 1. Notice, Version 2 may resolve the issues via issue #2157.

Webpack

Use postcss-loader in webpack.config.js:

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'style-loader',
          },
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
            }
          },
          {
            loader: 'postcss-loader'
          }
        ]
      }
    ]
  }
}

Then create postcss.config.js:

module.exports = {
  plugins: [
    require('autoprefixer'),
    require('postcss-nested')
  ]
}

Gulp

Use gulp-postcss and gulp-sourcemaps.

gulp.task('css', () => {
  const postcss    = require('gulp-postcss')
  const sourcemaps = require('gulp-sourcemaps')

  return gulp.src('src/**/*.css')
    .pipe( sourcemaps.init() )
    .pipe( postcss([ require('autoprefixer'), require('postcss-nested') ]) )
    .pipe( sourcemaps.write('.') )
    .pipe( gulp.dest('build/') )
})

npm Scripts

To use PostCSS from your command-line interface or with npm scripts there is postcss-cli.

postcss --use autoprefixer -o main.css css/*.css

Browser

If you want to compile CSS string in browser (for instance, in live edit tools like CodePen), just use Browserify or webpack. They will pack PostCSS and plugins files into a single file.

To apply PostCSS plugins to React Inline Styles, JSS, Radium and other CSS-in-JS, you can use postcss-js and transforms style objects.

const postcss  = require('postcss-js')
const prefixer = postcss.sync([ require('autoprefixer') ])

prefixer({ display: 'flex' }) //=> { display: ['-webkit-box', '-webkit-flex', '-ms-flexbox', 'flex'] }

Deno

PostCSS also supports Deno:

import postcss from 'https://deno.land/x/postcss/mod.js'
import autoprefixer from 'https://jspm.dev/autoprefixer'

const result = await postcss([autoprefixer]).process(css)

Runners

JS API

For other environments, you can use the JS API:

const autoprefixer = require('autoprefixer')
const postcss = require('postcss')
const postcssNested = require('postcss-nested')
const fs = require('fs')

fs.readFile('src/app.css', (err, css) => {
  postcss([autoprefixer, postcssNested])
    .process(css, { from: 'src/app.css', to: 'dest/app.css' })
    .then(result => {
      fs.writeFile('dest/app.css', result.css, () => true)
      if ( result.map ) {
        fs.writeFile('dest/app.css.map', result.map.toString(), () => true)
      }
    })
})

Read the PostCSS API documentation for more details about the JS API.

All PostCSS runners should pass PostCSS Runner Guidelines.

Options

Most PostCSS runners accept two parameters:

  • An array of plugins.
  • An object of options.

Common options:

  • syntax: an object providing a syntax parser and a stringifier.
  • parser: a special syntax parser (for example, SCSS).
  • stringifier: a special syntax output generator (for example, Midas).
  • map: source map options.
  • from: the input file name (most runners set it automatically).
  • to: the output file name (most runners set it automatically).

Treat Warnings as Errors

In some situations it might be helpful to fail the build on any warning from PostCSS or one of its plugins. This guarantees that no warnings go unnoticed, and helps to avoid bugs. While there is no option to enable treating warnings as errors, it can easily be done by adding postcss-fail-on-warn plugin in the end of PostCSS plugins:

module.exports = {
  plugins: [
    require('autoprefixer'),
    require('postcss-fail-on-warn')
  ]
}

Editors & IDE Integration

VS Code

Atom

Sublime Text

Vim

WebStorm

To get support for PostCSS in WebStorm and other JetBrains IDEs you need to install this plugin.

Security Contact

To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.

For Enterprise

Available as part of the Tidelift Subscription.

The maintainers of postcss and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Github

https://github.com/postcss/postcss

Comments(16)

  • 1

    Common configs

    I just read the thread about the upcoming Babel 6.0 https://github.com/babel/babel/issues/2168

    tl;dr: Instead of being something similar to cssnext, Babel will become an engine, like PostCSS.

    I think this is a really nice road. PostCSS is already on it, so it's awesome. I was trying hard to make cssnext THE solution, but I guess I failed, people like modularity (and don't care that much about standard). cssnext has too many problem to handle with potential specs changes (that's why Babel is moving from a solution with many transformers to none).

    The idea of preset for Babel seems really the way to go ("preset-es2015" :heart:). The thing is, cssnext can't do that, because csswg is working on different modules. So I guess it's time to think about deprecating cssnext. The thing I love in both cssnext and babel is that they have a cli builtin and an easy management for conf (.babelrc, I am currently working on .cssnextrc - but I am not sure I should finish my work). What I am offering here (and really think it will be just awesome for PostCSS) is to bring you back my work to easily add a CLI builtin + a .postcssrc. Direct benefits are:

    • cli builtin is a really nice thing, especially to share postcssified code (this will easily solve #434) because this way, you can add a prepublish hook to publish transformed code to npm for example.
    • all postcss runners will have less work to do (every plugins might be defined in .postcssrc) and PostCSS will handle a same config the same way from all runners. This is a great added value we can bring.

    This will not require a lot of code in postcss because work is already done as separate module (or will be in a couple of days):

    • a recently made a ._rc loader that support YAML, JSON and JavaScript ! (module.exports = {/_config*/} like webpack, very nice to configure plugins) https://github.com/MoOx/rc-loader
    • I am exporting the cli+watcher of cssnext for stylelint (see https://github.com/stylelint/stylelint/issues/288) as a standalone module, so using this into PostCSS will probably be just a small file of javascript.

    Discussion is open !

  • 2

    SugarSS syntax

    Many users asked about some compact syntax like Sass or Styles. In PostCSS 5.0 we can make it, it is good time to find the best compact syntax.

    My requirements:

    • No ;.
    • Short syntax for comments.
    • Allows multiline values.
    • Consistency (not like Stylus, when you can write in different syntax).
  • 3

    Mixin plugins

    What mixin plugins we should add for PostCSS?

    Sass like syntax (will be very important for ex-Sass users):

    @mixin clearfix {
      &:after {
        content: "";
        clear: both;
      }
    }
    
    @mixin border(width) {
      border: width solid black;
    }
    
    .box {
      @include clearfix;
      @include border(2px);
      width: 500px
    }
    

    Stylus (better CSS syntax support, but you didn’t know where you have mixin and where you have some new property):

    .box {
        clearfix: 1;
        border: 2px;
    }
    

    /cc @yisibl @MoOx @morishitter

  • 4

    CLI API?

    I'm not finding much in the way of a CLI API, but I'd like to. Goal: to use PostCSS straight from NPM. http://blog.keithcirkel.co.uk/how-to-use-npm-as-a-build-tool/

  • 5

    DeprecationWarning: Use of deprecated folder mapping "./" in the "exports" field module resolution of the package at G:\SNWS\sn-micro-front-web-project-template\node_modules\postcss\package.json.

    This is not a error!!!

    operating system: Windows 10, node: 15.1.0, npm: 6.14.8, webpack: 5.4.0, postcss: 8.1.4

    This is only a warning issued by "nodejs". It is recommended to make corrections according to the warning, because some writing methods are not recommended.

    image

  • 6

    Custom parsers

    1. Someone want to parser SCSS with // one line comment.
    2. I want to have light syntax without ; (and maybe with one line comment).
    3. Some legacy code requires Safe Mode parser to forget big CSS issues. Not it is in parser by options and it is not good solution.

    Maybe we should allow PostCSS to change parsers:

    postcss.process(css);
    postcss.process(css, { parser: SafeParser });
    

    All parser should return same AST, but them can parse any syntax.

    /cc @lydell @MoOx @rvanes

  • 7

    Request for Autoloading Plugins as a Core Functionality

    Hi, is there some interest in making it possible for postcss to auto-load plugins based on a config obj either inline, from a separate js | json file or a section in pkg.json (e.g pkg.postcss)?

    The plugin names are written without the postcss- prefix and hyphen delimited names should be written in camelCase. The postition in the plugins array is determined by the plugins[i].key e.g => [plugin1(), plugin2(), pluginName3()]. In other words it matters in which order you declare your options ;).

    Inline (not that useful, but for demonstration)

     const postcss = require('postcss')
    
    // Same as 
    // const plugin1 = require('poscss-plugin1')({})
    // const plugin2 = require('poscss-plugin2')({})
    // const plugin3 = require('poscss-plugin-name3')({})
    const plugins = {
     plugin1: {/* options */},
     plugin2: {/* options */},
     pluginName3: {/* options */}
    }
    
    postcss(plugins).process...
    

    plugins.js

    module.exports = { //order
      plugin1: {},  //1.
      plugin2: {}   //2.
      pluginName3: {}   //3.
    }
    

    plugins.json

    {
      "plugin1": {},
      "plugin2": {} ,
      "pluginName3": {}
    }
    

    package.json

    "postcss": {
      "plugin1": {},
      "plugin2": {}  
    }
    
    // from 
    postcss(require('postcss-loads-plugins')('./plugins')).process...
    // to
    postcss('./plugins').process…
    

    The way it which it's handled at the moment is not affected in anyways. It's just an attempt to make it possible to pass an obj or string directly to the loader API and then plugin requires and array scaffolding is handled in core.

  • 8

    Plugin Guidelines discussion

    Here is a current draft of PostCSS Plugin Guidelines. I just finish first version of draft and totally open for any feedback. What we should add, remove, change?

    This document is only for mandatory rules. We will have separated document for Best Practices (like “try to use W3C draft instead of own syntax”).

    I think my draft contains too any grammar mistakes. Let’s fix them after we will fix document content.

    This rules will be mandatory for all plugin developers. Speak now or forever hold your peace.

    /cc @MoOx @ben-eb @yisibl @morishitter @davidtheclark @antyakushev @btholt @magsout @corysimmons @jo-asakura @simonsmith @pascalduez @iamvdo @geddski

  • 9

    Improve source maps API

    I have some ideas for the source maps API that will:

    • Clean the options up a bit.
    • Nicely add requested features.
    • Allow better source path handling.
    • Still not make too much difference for the user.
    • Preserve all current default behavior.

    I propose:

    • Enhance options.map:
      • If omitted, default to false. (Like now.)
      • false → don’t generate source map. (Like now.)
      • true → equivalent to {}.
      • Deprecate passing previous map, such as map: sassMap. But allow it until it is removed.
      • If an object: Generate source map. Options:
        • map.annotation:
          • If omitted, default to 'preserve'.
          • 'preserve' → Use same annotation type as input. (Like mapAnnotation: true now.)
          • 'none' → No annotation. (Like mapAnnotation: false now.)
          • 'inline' → Inline the source map into the annotation. (Like inlineMap: true now.)
          • 'path' → Use map.path as annotation. (New feature, though kind of possible now, too, at least partly…)
        • map.path:
          • If omitted, default to options.to + '.map'. (This is actually the current behavior, more or less: We always assume that the source map will either be saved next to the CSS, or inlined into the CSS.)
          • It is the path to the intended location where the source map will be written to disk. This allows to store the source map somewhere else than only next to the CSS or inlined into the CSS, and still have correct source paths. (New feature, inspired by https://github.com/reworkcss/css-stringify/issues/39/https://github.com/reworkcss/css-stringify/issues/40.)
          • Relative to options.to.
          • Ignored and set to opitons.to if map.annotation is 'inline', or if map.annotation is 'preserve' and the previous annotation had the previous source map inlined.
        • map.setSourceContents:
          • If omitted, default to false.
          • false → Don’ set the sourceContents property of the source map. (Like now.)
          • true → Set the sourceContents property to the input CSS. (New feature, as requested by #31.)
        • Perhaps: map.sourceRoot:
          • If omitted, don’t set the sourceRoot property of the source map. (Like now.)
          • Otherwise, set the sourceRoot property of the source map to map.sourceRoot. (New feature. It is very easy to add (new mozilla.SourceMapGenerator({sourceRoot: options.map.sourceRoot})), but YAGNI?)
        • Perhaps map.previous:
          • Intended as a replacement for map: sassMap, for example. However, does anyone use this? YAGNI?
          • If omitted, default to null (or possibly true).
          • null → Simply no previous source map.
          • Perhaps: false → Disable previous source map detection, but still generate a source map. If so: true → Autodetect previous source map (Like now.) YAGNI?
          • If an object:
            • previous.map:
              • If omitted, set options.previous to its default value (null or possibly true; see above).
              • It is a previous map, like map: sassMap now.
            • previous.path:
              • If omitted, default to '.'.
              • It is the path to the previous map. It is needed to correctly rewrite the source paths of the previous map to be relative to options.map.path.
            • Otherwise: previous.map = {map: previous.map}. (Like map: sassMap now.)
            • Or perhaps we should simply let map.previous be a previous source map (nothing more) and don’t care if it is not perfect.
    • Deprecate options.mapAnnotation. Until it is removed:
      • falseoptions.map.annotation = 'none' (unless options.map.annotation was already set).
      • trueoptions.map.annotation = 'preserve' (unless options.map.annotation was already set).
    • Deprecate options.inlineMap. Until it is removed:
      • false → Nothing to do.
      • trueoptions.map.annotation = 'inline' (unless options.map.annotation was already set).
    • Deprecate trying to autodetect previous map by looking for options.from + '.map'. I don’t think that case exists in reality. The user could possibly pass from: from, map: {previous: {map: fs.readFileSync(from + '.map'), path: from + '.map'}} instead.

    What do you think? I could make a PR.

  • 10

    Event based API

    Right now PostCSS behavior depends on plugin order.

    For example, if you put postcss-siple-vars before postcss-mixin, it will broke mixins.

    @1j01 told about same problem with functions.

    And potentially we may have a loop problem. We need to find solution.

  • 11

    Import Plugin

    Right now we have a some mess in @import plugins:

    • postcss-import doesn’t provide out-of-box solution for most of developers and still looking a maintaier.
    • postcss-easy-import has more features, but base on top of frozen postcss-import
    • postcss-partial-import is good, but has not all of user request’s features.

    Right now I am a fan of postcss-smart-import, because it has active development and has a lot of features.

    Anyway, right now we have a UX problem, because new PostCSS users doesn’t know what to add and have many problems with @import. As result they become disappointment of entire PostCSS ecosystem (“plugins hell”, “bad support”) and leave it.

    I think that we should choice one plugin and deprecate others one. We could move some missed features to winner plugin. Maybe we should also rename winner plugin to postcss-import.

    @MoOx @TrySound @jonathantneal @swernerx what do you think?

  • 12

    How to use `postcss.parse` with plugins

    Hi,

    I've had a hard time finding this:

    if (plugins.length > 0) {
      return postcss(plugins).process(css).root
    } else {
      return postcss.parse(css)
    }
    

    Or how to use .parse with plugins.

    Maybe you should document it. I opened this issue to help whoever is looking for it.

    Closing now because not an issue.

  • 13

    Make types of various `raws` properties consistent

    Different types of nodes specify different (mostly optional) properties on raws. If there's truly nothing that can be guaranteed about raws, it probably makes more sense to just have all node types use any, but if not, it probably makes sense to have a common interface defining each property that the default CSS parser uses.

  • 14

    Consider adding an AnyContainer type to allow narrowing

    Similar to the AnyNode type, there should be an AnyContainer type that allows you to narrow it to a specific type of container.

    The definition would probably look something like:

    type AnyContainer = (AtRule|Rule|Root|Document)&Container<AnyNode>
    
  • 15

    Node.before() inserts after if the new node is already a sibling

    Test case:

    const postcss = require("postcss");
    
    const root = postcss.parse("@foo; @bar; @baz");
    const foo = root.nodes[0];
    const baz = root.nodes[2];
    baz.before(foo);
    root.toString(); // expected: "@bar; @foo; @baz"
                     // actually: "@bar; @baz; @foo"
    

    It looks like the index calculation gets stale once the new node is removed from its original location.

  • 16

    Document how to declare a PostCSS plugin in an ES6/TypeScript module

    It's currently unclear how to properly declare a PostCSS module using ES6 module syntax (which TypeScript also uses idiomatically). The suggested module.exports isn't idiomatic in these systems.