Postcss-loader

Using PostCSS Along with Task-runners and Sass

PostCSS can be incorporated into your workflow rather easily. As mentioned already, it integrates perfectly well with task runners like Grunt, Gulp, or Webpack, and it can even be used with NPM scripts. An example of using PostCSS along with Sass and Gulp is as simple as the following code snippet:


Let’s deconstruct the above code example.

It stores references to all of the needed modules (Gulp, Contact CSS, Sass, PostCSS, and CSSNext) in a series of variables.

Then, it registers a new Gulp task called . This task watches for files that are in with the extension (regardless of how deep in the subdirectory structure they are), Sass compiles them, and concatenates all of them to a single file.

Once the file is generated, it is passed to PostCSS to transpile all of the PostCSS (and plugin) related code to the actual CSS, and then the resulting file is placed in .

OK, so setting up PostCSS with a task runner and a preprocessor is great, but is that enough to justify working with PostCSS in the first place?

Let’s put it like this: While Sass is stable, mature, and has a huge community behind it, we might want to use PostCSS for plugins like Autoprefixer, for example. Yes, we could use the standalone Autoprefixer library, but the advantages of using Autoprefixer as a PostCSS plugin is the possibility to add more plugins to the workflow later on and avoid extraneous dependencies on a boatload of JavaScript libraries.

This approach also allows us to use unprefixed properties and have them prefixed based on the values fetched from APIs, like the one from Can I Use, something that is hardly achievable using Sass alone. This is pretty useful if we’re trying to avoid complex mixins that might not be the best way to prefix code.

The most common way to integrate PostCSS into your current workflow, if you’re already using Sass, is to pass the compiled output of your or file through PostCSS and its plugins. This will generate another CSS file that has the output of both Sass and PostCSS.

If you’re using a task runner, using PostCSS is as easy as adding it to the pipeline of tasks you currently have, right after compiling your or file (or the files of your preprocessor of choice).

PostCSS plays well with others, and can be a relief for some major pain points we as developers experience every day.

Let’s take a look at another example of PostCSS (and a couple of plugins likes CSSNext and Autoprefixer) and Sass working together. You could have the following code:

This snippet of the code has vanilla CSS and Sass syntax. Custom properties, as of the day of the writing of this article, are still in Candidate Recommendation (CR) status, and here’s where the CSSNext plugin for PostCSS comes into action.

This plugin will be in charge of turning stuff like custom properties into today’s CSS. Something similar will happen to the property, which will be auto-prefixed by the Autoprefixer plugin. The code written earlier will then result in something like:

PostCss в двух словах

Так что же такое PostCss? Лучше описание, которое приходит с проекта на  ГитХабе:

В двух словах, PostCss берет CSS и превращает в вид данных, которые можно изменять с помощью Яваскрипт. Основанные на Яваскрипт плагины, позволяют изменять код. PostCss сам по себе ничего не изменяет, он всего лишь прокладывает путь для плагинов, которые делают изменения и траснформации для которого они созданы.

Практически не существует ограничений в манипуляции плагинами для PostCss, которые можно применить к CSS. Если вы можете подумать о чем либо, то это можно сделать с помощью плагинов для PostCss.

Плагины PostCss, могут вести себя как препроцессоры: могут оптимизировать и добавлять префиксы в код, могут добавлять синтаксис из будущих спецификаций, могут выполнять проверку, могут производить переменные и логику, можно создавать сетки…этот список очень длинный и разнообразный.

Options

The option determines which CSS features to polyfill, based upon their stability in the process of becoming implemented web standards.

postcssPresetEnv({ stage})

The option enables or disables specific polyfills by ID. Passing to a specific feature ID will enable its polyfill, while passing will disable it.

postcssPresetEnv({  stage3,  features{'nesting-rules'true}})

Passing an object to a specific feature ID will both enable and configure it.

postcssPresetEnv({  stage3,  features{'color-mod-function'{ unresolved'warn'}}})

The option determines which polyfills are required based upon the browsers you are supporting.

The option should only be used when a standard browserslist configuration is not available.

postcssPresetEnv({ browsers'last 2 versions'})

The and keys allow you to insert other PostCSS plugins into the chain. This is only useful if you are also using sugary PostCSS plugins that must execute before or after certain polyfills. Both and support chaining one or multiple plugins.

importpostcssSimpleVarsfrom'postcss-simple-vars';postcssPresetEnv({  insertBefore{'all-property' postcssSimpleVars}})
postcssPresetEnv({  autoprefixer{ gridtrue}})

Passing disables autoprefixer.

The option determines whether all plugins should receive a option, which may preserve or remove otherwise-polyfilled CSS. By default, this option is not configured.

postcssPresetEnv({  preservefalse});

The option specifies sources where variables like Custom Media, Custom Properties, Custom Selectors, and Environment Variables can be imported from, which might be CSS, JS, and JSON files, functions, and directly passed objects.

postcssPresetEnv({  importFrom'path/to/file.css'});

Multiple sources can be passed into this option, and they will be parsed in the order they are received. JavaScript files, JSON files, functions, and objects will use different namespaces to import different kinds of variables.

postcssPresetEnv({  importFrom'path/to/file.css','and/then/this.js','and/then/that.json',{      customMedia{'--small-viewport''(max-width: 30em)'},      customProperties{'--color''red'},      customSelectors{':--heading''h1, h2, h3'},      environmentVariables{'--branding-padding''20px'}},()=>{constcustomMedia={'--small-viewport''(max-width: 30em)'};constcustomProperties={'--color''red'};constcustomSelectors={':--heading''h1, h2, h3'};constenvironmentVariables={'--branding-padding''20px'};return{ customMedia, customProperties, customSelectors, environmentVariables };}});

The option specifies destinations where variables like Custom Media, Custom Properties, Custom Selectors, and Environment Variables can be exported to, which might be CSS, JS, and JSON files, functions, and directly passed objects.

postcssPresetEnv({  exportTo'path/to/file.css'});

Multiple destinations can be passed into this option as well, and they will be parsed in the order they are received. JavaScript files, JSON files, and objects will use different namespaces to import different kinds of variables.

constcachedObject={};postcssPresetEnv({  exportTo'path/to/file.css','and/then/this.js','and/then/that.json',    cachedObject,variables=>{if('customProperties'in variables){}Object.assign(cachedObject, variables);}});

Should I Ditch My Current CSS Processor in Order to Use PostCSS?

Well, that depends on what you’re looking for.

It is common to see both Sass and PostCSS used at the same time, since it is easier for newcomers to work with some of the tools that pre/post-processors offer out of the box, along with PostCSS plugins’ features. Using them side-by-side can also avoid rebuilding a predefined workflow with relatively new, and most likely unknown, tools, while providing a way to maintain current processor-dependant implementations (like Sass mixins, extends, the parent selector, placeholder selectors, and so on).

Related: Maintain Control: A Guide to Webpack and React, Pt. 2

Usage

npm install postcss-preset-env --save-dev
importpostcssPresetEnvfrom'postcss-preset-env';postcssPresetEnv.process(YOUR_CSS);
npm install postcss --save-dev
importpostcssfrom'gulp-postcss';importpostcssPresetEnvfrom'postcss-preset-env';postcss(postcssPresetEnv()).process(YOUR_CSS);
npm install postcss-loader --save-dev
importpostcssPresetEnvfrom'postcss-preset-env';exportdefault{  module{    rules{        test\.css$,        use'style-loader',{ loader'css-loader', options{ importLoaders1}},{ loader'postcss-loader', options{            ident'postcss',plugins()=>postcssPresetEnv()}}}}};
npm install react-app-rewired react-app-rewire-postcss --save-dev
importreactAppRewirePostcssfrom'react-app-rewire-postcss';importpostcssPresetEnvfrom'postcss-preset-env';exportdefaultconfig=>reactAppRewirePostcss(config,{plugins()=>postcssPresetEnv()});
npm install gulp-postcss --save-dev
importpostcssfrom'gulp-postcss';importpostcssPresetEnvfrom'postcss-preset-env';gulp.task('css',()=>gulp.src('./src/*.css').pipe(postcss(postcssPresetEnv())).pipe(gulp.dest('.')));
npm install grunt-postcss --save-dev
importpostcssPresetEnvfrom'postcss-preset-env';grunt.loadNpmTasks('grunt-postcss');grunt.initConfig({  postcss{    options{      usepostcssPresetEnv()},    dist{      src'*.css'}}});

Examples

webpack.config.js

webpack.config.js

This loader cannot be used with out of the box due to the way processes file imports. To make them work properly, either add the css-loader’s option.

webpack.config.js

or use postcss-modules instead of .

If you want to process styles written in JavaScript, use the postcss-js parser.

webpack.config.js

As result you will be able to write styles in the following way

Extract CSS

To write a asset from the postcss plugin to the webpack’s output file system, need to add a message in . The message should contain the following fields:

  • = — Message type (require, should be equal )
  • — file name (require)
  • — file content (require)
  • — sourceMap
  • — asset info

There are two way to add dependencies:

  1. (Recommended). Postcss plugin should emit message in .

The message should contain the following fields:

  • = — Message type (require, should be equal )
  • — absolute file path (require)
  1. Pass in plugin.

Usage

npm install postcss-preset-env --save-dev
importpostcssPresetEnvfrom'postcss-preset-env';postcssPresetEnv.process(YOUR_CSS);
npm install postcss --save-dev
importpostcssfrom'gulp-postcss';importpostcssPresetEnvfrom'postcss-preset-env';postcss(postcssPresetEnv()).process(YOUR_CSS);
npm install postcss-loader --save-dev
importpostcssPresetEnvfrom'postcss-preset-env';exportdefault{  module{    rules{        test\.css$,        use'style-loader',{ loader'css-loader', options{ importLoaders1}},{ loader'postcss-loader', options{            ident'postcss',plugins()=>postcssPresetEnv()}}}}};
npm install react-app-rewired react-app-rewire-postcss --save-dev
importreactAppRewirePostcssfrom'react-app-rewire-postcss';importpostcssPresetEnvfrom'postcss-preset-env';exportdefaultconfig=>reactAppRewirePostcss(config,{plugins()=>postcssPresetEnv()});
npm install gulp-postcss --save-dev
importpostcssfrom'gulp-postcss';importpostcssPresetEnvfrom'postcss-preset-env';gulp.task('css',()=>gulp.src('./src/*.css').pipe(postcss(postcssPresetEnv())).pipe(gulp.dest('.')));
npm install grunt-postcss --save-dev
importpostcssPresetEnvfrom'postcss-preset-env';grunt.loadNpmTasks('grunt-postcss');grunt.initConfig({  postcss{    options{      usepostcssPresetEnv()},    dist{      src'*.css'}}});

Usage

npm install postcss-preset-env --save-dev
importpostcssPresetEnvfrom'postcss-preset-env';postcssPresetEnv.process(YOUR_CSS);
npm install postcss --save-dev
importpostcssfrom'gulp-postcss';importpostcssPresetEnvfrom'postcss-preset-env';postcss(postcssPresetEnv()).process(YOUR_CSS);
npm install postcss-loader --save-dev
importpostcssPresetEnvfrom'postcss-preset-env';exportdefault{  module{    rules{        test\.css$,        use'style-loader',{ loader'css-loader', options{ importLoaders1}},{ loader'postcss-loader', options{            ident'postcss',plugins()=>postcssPresetEnv()}}}}};
npm install react-app-rewired react-app-rewire-postcss --save-dev
importreactAppRewirePostcssfrom'react-app-rewire-postcss';importpostcssPresetEnvfrom'postcss-preset-env';exportdefaultconfig=>reactAppRewirePostcss(config,{plugins()=>postcssPresetEnv()});
npm install gulp-postcss --save-dev
importpostcssfrom'gulp-postcss';importpostcssPresetEnvfrom'postcss-preset-env';gulp.task('css',()=>gulp.src('./src/*.css').pipe(postcss(postcssPresetEnv())).pipe(gulp.dest('.')));
npm install grunt-postcss --save-dev
importpostcssPresetEnvfrom'postcss-preset-env';grunt.loadNpmTasks('grunt-postcss');grunt.initConfig({  postcss{    options{      usepostcssPresetEnv()},    dist{      src'*.css'}}});

4Process your CSS with Tailwind

Using Tailwind with PostCSS

For most projects, you’ll want to add Tailwind as a PostCSS plugin in your build chain.


Generally this means adding Tailwind as a plugin in your file:

We’ve included more specific instructions for a few popular tools below, but for instructions on getting started with PostCSS in general, see the .

Using Tailwind CLI

For simple projects or just giving Tailwind a spin, you can use the Tailwind CLI tool to process your CSS:

Use the command to learn more about the various CLI options.

Build Tool Examples

We’ve included some basic examples of setting up Tailwind with common build tools below, but also look at our setup-examples repository for even more examples that you can even clone and play with locally.

Add as a plugin in your file:

…or include it directly in your postcss-loader configuration in your file:

Laravel Mix

If you’re writing your project in plain CSS, use Mix’s method to process your CSS and include as a plugin:

If you’re using a preprocessor, use the method to add as a PostCSS plugin:

Note for Sass users: Due to an unresolved issue with one of Mix’s dependencies, to use Sass with Tailwind you’ll need to disable :

For more information on what this feature does and the implications of disabling it, .

Create a file, add as a plugin and pass the path to your config file:

Within , create a style entry and enable the PostCSS loader.

You can also pass options into the PostCSS loader by passing a callback, as per the Encore PostCSS docs:

Note for Sass users: Due to an unresolved issue with one of Encore’s dependencies, to use Sass with Tailwind you’ll need to disable :

Plugins

The plugin will be loaded with defaults

'postcss-plugin'{}||null

.postcssrc.js

module.exports={  plugins{'postcss-plugin'{}||null}}

The plugin will be loaded with given options

'postcss-plugin'{ option'', option''}

.postcssrc.js

module.exports={  plugins{'postcss-plugin'{ option'', option''}}}

The plugin will not be loaded

'postcss-plugin'false

.postcssrc.js

module.exports={  plugins{'postcss-plugin'false}}

Plugin execution order is determined by declaration in the plugins section (top-down)

{  plugins{'postcss-plugin'{},'postcss-plugin'{},'postcss-plugin'{}}}

Options

The option determines which CSS features to polyfill, based upon their stability in the process of becoming implemented web standards. The stages are 0 through 4.

postcssPresetEnv({  stage})

The option enables or disables specific polyfills. Passing to a specific feature id will enable its polyfill, while passing will disable it.

postcssPresetEnv({  stage3,  features{'nesting-rules'true}})

Passing an object to a specific feature id will enable and configure it.

postcssPresetEnv({  stage3,  features{'color-mod-function'{      unresolved'warn'}}})

The option should only be used when a standard browserslist configuration is not available.

postcssPresetEnv({  browsers'last 2 versions'})

The and keys allow you to insert other PostCSS plugins into the chain. This is only useful if you are also using sugary PostCSS plugins that must execute before or after certain polyfills. Both and support chaining one or multiple plugins.

importpostcssSimpleVarsfrom'postcss-simple-vars';postcssPresetEnv({  insertBefore{'all-property' postcssSimpleVars}})

Usage

npm i -S|-D postcss-plugin

Install all required postcss plugins and save them to your package.json /

Then create a postcss config file by choosing one of the following formats

Create a section in your projects

{"postcss"{"parser""sugarss","map"false,"plugins"{"postcss-plugin"{}}}}

Create a file in JSON or YAML format

{"parser""sugarss","map"false,"plugins"{"postcss-plugin"{}}}
parsersugarssmapfalsepluginspostcss-plugin{}

You may need some logic within your config. In this case create JS file named or

You can export the config as an

.postcssrc.js

module.exports={  parser'sugarss',  mapfalse,  plugins{'postcss-plugin'{}}}

Or export a that returns the config (more about the param below)

.postcssrc.js

module.exports=(ctx)=>({  parserctx.parser?'sugarss'false,  mapctx.env==='development'?ctx.mapfalse,  plugins{'postcss-plugin'ctx.options.plugin}})

Plugins can be loaded either using an or an


.postcssrc.js

module.exports=({ env })=>({...options  plugins{'postcss-plugin' env ==='production'?{}false}})

.postcssrc.js

module.exports=({ env })=>({...options  plugins    env ==='production'?require('postcss-plugin')()false})

Examples

postcss.config.js

module.exports=(ctx)=>({  parserctx.parser?'sugarss'false,  mapctx.env==='development'?ctx.mapfalse,  plugins{'postcss-import'{},'postcss-nested'{},    cssnanoctx.env==='production'?{}false}})
"scripts"{"build""NODE_ENV=production node postcss","start""NODE_ENV=development node postcss"}
const{readFileSync}=require('fs')constpostcss=require('postcss')constpostcssrc=require('postcss-load-config')constcss=readFileSync('index.sss','utf8')constctx={ parsertrue, map'inline'}postcssrc(ctx).then(({ plugins, options })=>{postcss(plugins).process(css, options).then((result)=>console.log(result.css))})
const{readFileSync}=require('fs')constpostcss=require('postcss')constpostcssrc=require('postcss-load-config')constcss=readFileSync('index.sss','utf8')constctx={ parsertrue, map'inline'}const{plugins,options}=postcssrc.sync(ctx)
"scripts"{"build""NODE_ENV=production gulp","start""NODE_ENV=development gulp"}
const{task,src,dest,series,watch}=require('gulp')constpostcss=require('gulp-postcssrc')constcss=()=>{src('src/*.css').pipe(postcss()).pipe(dest('dest'))})task('watch',()=>{watch('src/*.css','postcss.config.js', css)})task('default',series(css,'watch'))
"scripts"{"build""NODE_ENV=production webpack","start""NODE_ENV=development webpack-dev-server"}

webpack.config.js

module.exports=(env)=>({  module{    rules{        test\.css$,        use'style-loader','css-loader','postcss-loader'}}})

Examples

Assets

The following can load CSS files, embed small PNG/JPG/GIF/SVG images as well as fonts as Data URLs and copy larger files to the output directory.

webpack.config.js

Extract

For production builds it’s recommended to extract the CSS from your bundle being able to use parallel loading of CSS/JS resources later on.

  • This can be achieved by using the mini-css-extract-plugin to extract the CSS when running in production mode.

  • As an alternative, if seeking better development performance and css outputs that mimic production. extract-css-chunks-webpack-plugin offers a hot module reload friendly, extended version of mini-css-extract-plugin. HMR real CSS files in dev, works like mini-css in non-dev

Pure CSS, CSS modules and PostCSS

When you have pure CSS (without CSS modules), CSS modules and PostCSS in your project you can use this setup:

webpack.config.js

index.css

webpack.config.js

Separating -only and features

The following setup is an example of allowing features only (such as and ) without using further functionality by setting option for all files that do not match naming convention. This is for reference as having features applied to all files was default behavior before v4. Meanwhile all files matching are treated as in this example.

An example case is assumed where a project requires canvas drawing variables to be synchronized with CSS — canvas drawing uses the same color (set by color name in JavaScript) as HTML background (set by class name in CSS).

webpack.config.js

variables.scss

File treated as -only.

Component.module.scss

File treated as .

Component.jsx

Using both functionality as well as SCSS variables directly in JavaScript.

Usage

npm install postcss-preset-env --save-dev
importpostcssPresetEnvfrom'postcss-preset-env';postcssPresetEnv.process(YOUR_CSS);
npm install postcss --save-dev
importpostcssfrom'gulp-postcss';importpostcssPresetEnvfrom'postcss-preset-env';postcss(postcssPresetEnv()).process(YOUR_CSS);
npm install postcss-loader --save-dev
importpostcssPresetEnvfrom'postcss-preset-env';exportdefault{  module{    rules{        test\.css$,        use'style-loader',{ loader'css-loader', options{ importLoaders1}},{ loader'postcss-loader', options{            ident'postcss',plugins()=>postcssPresetEnv()}}}}};
npm install react-app-rewired react-app-rewire-postcss --save-dev
importreactAppRewirePostcssfrom'react-app-rewire-postcss';importpostcssPresetEnvfrom'postcss-preset-env';exportdefaultconfig=>reactAppRewirePostcss(config,{plugins()=>postcssPresetEnv()});
npm install gulp-postcss --save-dev
importpostcssfrom'gulp-postcss';importpostcssPresetEnvfrom'postcss-preset-env';gulp.task('css',()=>gulp.src('./src/*.css').pipe(postcss(postcssPresetEnv())).pipe(gulp.dest('.')));
npm install grunt-postcss --save-dev
importpostcssPresetEnvfrom'postcss-preset-env';grunt.loadNpmTasks('grunt-postcss');grunt.initConfig({  postcss{    options{      usepostcssPresetEnv()},    dist{      src'*.css'}}});

Dissecting PostCSS-cssnext

If we delve into the PostCSS-cssnext repository on GitHub, we can see just how modular this plug-in is. Inside the src/features.js file, we’ll see that the code for each future CSS feature is enclosed within its own module named in accordance with the relevant CSS specification.

Because it’s a plug-in pack, PostCSS-cssnext is bundled with PostCSS plug-ins. This means that we could install these features individually if we so choose, although using PostCSS-cssnext means we don’t have to! For example, if we only wanted to use CSS custom properties, we could install it via like this:

For a full list of all the CSS features PostCSS-cssnext supports, head over to the dedicated features page on the PostCSS-cssnext website.

We should also note that PostCSS-cssnext comes bundled with autoprefixer and pixrem. Don’t worry if you’re unfamiliar with these tools. They are post-processors for creating cross-browser compatible CSS, and we are going to find out how they work soon.

Getting Started

To begin, you’ll need to install :

Then add the plugin to your config. For example:

file.js

webpack.config.js

Good loaders for requiring your assets are the file-loader and the url-loader which you should specify in your config (see ).

And run via your preferred method.

You can also use the css-loader results directly as a string, such as in Angular’s component style.


webpack.config.js

or

If there are SourceMaps, they will also be included in the result string.

If, for one reason or another, you need to extract CSS as a plain string resource (i.e. not wrapped in a JS module) you might want to check out the extract-loader. It’s useful when you, for instance, need to post process the CSS as a string.

webpack.config.js

История

Впервые идея модульного инструмента для CSS была предложена TJ Holowaychuk 1 сентября 2012 в проекте Rework. 28 февраля 2013 TJ рассказал о ней публично.

14 марта 2013 Андрей Ситник в компании «Злые марсиане» сделал расширение Автопрефиксер на базе Rework. Изначально расширение даже называлось «rework-vendors».

При росте Автопрефиксера были обнаружены проблемы в реализации Rework. Поэтому 7 сентября 2013 Андрей Ситник начал разработку PostCSS на основе идей Rework.

Через 3 месяца вышел первый плагин для PostCSS — grunt-pixrem. 22 декабря 2013 в версии 1.0 Автопрефиксер перешёл на PostCSS.

PostCSS активно использует тему алхимии в своей символике. Логотипом проекта является знак философского камня. Мажорные и минорные версии PostCSS получают имена демонов «Гоетии». Например, имя версии 1.0.0 — «Маркиз Декарабиа».

Usage

npm install postcss-preset-env --save-dev
importpostcssPresetEnvfrom'postcss-preset-env';postcssPresetEnv.process(YOUR_CSS);
npm install postcss --save-dev
importpostcssfrom'gulp-postcss';importpostcssPresetEnvfrom'postcss-preset-env';postcss(postcssPresetEnv()).process(YOUR_CSS);
npm install postcss-loader --save-dev
importpostcssPresetEnvfrom'postcss-preset-env';exportdefault{  module{    rules{        test\.css$,        use'style-loader',{ loader'css-loader', options{ importLoaders1}},{ loader'postcss-loader', options{            ident'postcss',plugins()=>postcssPresetEnv()}}}}};
npm install react-app-rewired react-app-rewire-postcss --save-dev
importreactAppRewirePostcssfrom'react-app-rewire-postcss';importpostcssPresetEnvfrom'postcss-preset-env';exportdefaultconfig=>reactAppRewirePostcss(config,{plugins()=>postcssPresetEnv()});
npm install gulp-postcss --save-dev
importpostcssfrom'gulp-postcss';importpostcssPresetEnvfrom'postcss-preset-env';gulp.task('css',()=>gulp.src('./src/*.css').pipe(postcss(postcssPresetEnv())).pipe(gulp.dest('.')));
npm install grunt-postcss --save-dev
importpostcssPresetEnvfrom'postcss-preset-env';grunt.loadNpmTasks('grunt-postcss');grunt.initConfig({  postcss{    options{      usepostcssPresetEnv()},    dist{      src'*.css'}}});

Скоро «Погружение в PostCss»

В этой серии уроков, мы шаг за шагом, будем изучать PostCss уроки:

  • Быстрый старт
  • Установка, настройка Gulp
  • Настройка Grunt
  • Анализ существующих плагинов.

Также мы рассмотрим, различные пути, как мы можем использовать PostCss

  • Кросс-браузерная совместимость
  • Минификация и оптимизация кода
  • Препроцессинг с PreCSS
  • Создаем свой собственный препроцессор
  • Совместная разработка с Stylus / Sass / LESS
  • БЭМ и  SUIT методология
  • Шорткаты и сокращения
  • Разнообразные сладости PostCss

И наконец, мы будем создавать свой собственный плагин PostCss.

Вы могли заметить, насколько мало существует уроков по использованию фичи в PostCss, называемой cssnext, (которая позволяет использовать «синтаксис будущего») особенно учитывая тот факт, что многие люди, считают его пост-обработкой.

Причина этого отсутствия является, продолжающаюся разработка cssnext, лидирующий проект, который все еще трансформируется и находится на стадии шлифовки. Таким образом, мы будем приглядывать за ним и публиковать свежие уроки по мере их выхода в свет.

Итак, приступим! В следующем уроке, будет вступление, «Быстрый старт» и будет показано как мы можем использовать PostCss. Увидимся здесь!

Usage

npm install gulp-postcss postcss-sorting --save-dev

Enable PostCSS Sorting within your Gulpfile:

var postcss =require('gulp-postcss');var sorting =require('postcss-sorting');gulp.task('css',function(){returngulp.src('./css/src/*.css').pipe(postcss(sorting({}))).pipe(gulp.dest('./css/src'));});
npm install grunt-postcss postcss-sorting --save-dev

Enable PostCSS Sorting within your Gruntfile:

grunt.loadNpmTasks('grunt-postcss');grunt.initConfig({    postcss{        options{            processorsrequire('postcss-sorting')({})},        dist{            src'css/*.css'}}});
npm install postcss-cli postcss-sorting --save-dev

Create an appropriate like this example:

module.exports=(ctx)=>({  plugins{'postcss-sorting'{'order''custom-properties','dollar-variables','declarations','at-rules','rules','properties-order''alphabetical','unspecified-properties-position''bottom'}}})

Or, simply add the section to your existing postcss-cli configuration file. Next, execute:

postcss -c postcss.config.js  --no-map -r your_css_file.css

Advanced usage

var gulp =require('gulp');var postcss =require('gulp-postcss');gulp.task('css',function(){functioncallback(file){return{            pluginsrequire('postcss-import')({ rootfile.dirname}),require('postcss-modules'),            options{                parserfile.extname==='.sss'?require('sugarss')false}}}returngulp.src('./src/*.css').pipe(postcss(callback)).pipe(gulp.dest('./dest'));});
var gulp =require('gulp');var postcss =require('gulp-postcss');gulp.task('css',function(){var contextOptions ={ modulestrue};returngulp.src('./src/*.css').pipe(postcss(contextOptions)).pipe(gulp.dest('./dest'));});
module.exports=function(ctx){var file =ctx.file;var options =ctx.options;return{        parserfile.extname==='.sss'?'sugarss'false,        plugins{'postcss-import'{ rootfile.dirname}'postcss-modules'options.modules?{}false}}})

Give PostCSS a Chance

PostCSS is the hot (well, sort of) new thing in the front-end development world. It has been widely adopted because it is not a pre/post-processor per se, and it is flexible enough to adapt to the environment it is being inserted into.

Much of the power of PostCSS resides in its plugins. If what you’re looking for is modularity, flexibility, and diversity, then this is the right tool for the job.

If you’re using task runners or bundlers, then adding PostCSS to your current flow will most likely be a piece of cake. Check the installation and usage guide, and you will probably find an easy way to integrate it with the tools you’re already using.

Many developers say it is here to stay, at least for the foreseeable future. PostCSS can have a great impact on how we structure our present-day CSS, and that could potentially lead to a much greater adoption of standards across the front-end web development community.

Authoring Plugins for PostCSS

As mentioned earlier, an attractive feature of PostCSS is the level of customization it allows. Thanks to its openness, authoring a custom plugin of your own for PostCSS to cover your particular needs is a rather simple task if you’re comfortable writing JavaScript.

The folks at PostCSS have a pretty solid list to start, and if you’re interested in developing a plugin check their recommended articles and guides. If you feel like you need to ask something, or discuss anything, Gitter is the best place to start.

PostCSS has its API with a pretty active base of followers on . Along with other community perks mentioned earlier in this post, this is what make the plugin creation process so much fun and such a collaborative activity.

So, to create a PostCSS plugin, we need to create a Node.js module. (Usually, PostCSS plugin folders in the directory are preceded by a prefix like “postcss-”, which is to make it explicit that they are modules that depend on PostCSS.)

For starters, in the file of the new plugin module, we need to include the the following code, which will be the wrapper of the plugin’s processing code:

We named the plugin replacecolors. The plugin will look for a keyword and replace it with the HEX color value:

The previous snippet just did the following:

  1. Using it iterated through all of the CSS rules that are in the current file we’re going through.
  2. Using it iterated through all of the CSS declarations that are inside the current file.
  3. Then it stored the declaration inside the declaration variable and checked if the string was in it. If it was, it replaced the whole declaration for the following CSS declaration: .

Once the plugin is ready, we can used it like this directly from the command line:

Or, for example, loaded in a Guplfile like this:

Basic PostCSS Usage

First, let’s cover some PostCSS basics and take a look how it is typically used. While PostCSS is extremely powerful when used with a task runner, like Gulp or Grunt, it can also be used directly from the command line by using the postcss-cli.

Let’s consider a simple example use case. Assume we’d like to use the postcss-color-rgba-fallback plugin in order to add a fallback HEX value to all of our RGBA formatted colors.

Once we’ve NPM installed , and , we need to run the following command:

With this instruction, we’re telling PostCSS to use the plugin, process whatever CSS is inside , and output it to .

OK, that was easy. Now, let’s look at a more complex example.


С этим читают