PostCSS
Introduction
PostCSS is a program that automates routine operations with CSS with
the help of extensions written in the JavaScript language.
It is used in the development of Wikipedia, Facebook and GitHub.
One of the most frequently downloaded tools for working with CSS from npm.
It was developed by Andrey Sitnik at the company «Evil Martians».
I use PostCSS together with Gulp, you can learn Gulp 4 in my article
Gulp 4
PostCSS installation
Let us install the PostCSS package for Gulp
npm install gulp-postcss --save-dev
At once let us add one of the most popular plugins for PostCSS - autoprefixer
Some developers use SASS and PostCSS at the same time precisely because of this plugin.
npm install autoprefixer --save-dev
Let us add to gulpfile.js
postcss = require('gulp-postcss'),
autoprefixer = require('autoprefixer')
And also make sure that autoprefixer and
gulp-postcss were added to devDependencies in the package.json file
"devDependencies": {
"autoprefixer": "^9.6.1",
"browser-sync": "^2.26.7",
"gulp": "^4.0.2",
"gulp-postcss": "^8.0.0",
"gulp-sass": "^4.0.2"
}
Let us edit the gulpfile.js file
we have added postcss and autoprfixer, we will remove sass and if there was anything extra - we will remove that too.
For practice let us rename the function style to styles - in how many places will this need to be done?
So far we have installed only autoprefixer, so assembling several files into one is not yet available to us.
let us specify the source file explicitly
const gulp = require('gulp')
,
postcss = require('gulp-postcss'),
autoprefixer = require('autoprefixer');
gulp.task('default', function(done) {
console.log("Gulp is running!");
done();
});
function styles() {
console.log("style is running!");
// 1. where is my dev css files
return gulp.src('./app/assets/styles/style.css')
// 2. pass that file through postcss compiller
.pipe(postcss([autoprefixer]))
// 3. where do I save the compiled CSS?
.pipe(gulp.dest('./app/temp/styles/style.css'))
}
function html() {
console.log("Some change in index.html happened!");
}
function watchFiles() {
gulp.watch("./app/assets/index.html", html);
gulp.watch("./app/assets/styles/**/*.css", styles);
}
exports.styles = styles;
exports.html = html;
exports.watch = watchFiles;
Let us run our new watch
gulp watch
Now, if we create a property that needs an autoprefix, for example columns and save the file
body {
padding: 27px;
margin: 12px;
columns: 300px 2;
}
The output - in the folder heiheiru/app/temp/styles/style.css we will see
body {
padding: 27px;
margin: 12px;
-moz-columns: 300px 2;
columns: 300px 2;
}
If you have run into difficulties - study the solution of the error with path
Variables in css
Let us install the postcss-simple-vars package
$ npm install postcss-simple-vars --save-dev
npm WARN heihei@1.0.0 No description
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9:
wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
+ postcss-simple-vars@5.0.2
added 1 package from 1 contributor and audited 10643 packages in 7.83s
found 0 vulnerabilities
Let us add a new constant
cssvars = require('postcss-simple-vars');
And insert it into the pipe of the styles function
.pipe(postcss([cssvars, autoprefixer]))
Now you can safely add to heiheiru/app/assets/styles/style.css
variables.
For example, colors. I need to set the main color for the section about Finland.
Let us name it finBlue and make it the same as the blue in the flag of Finland.
$finBlue: #002f6c;
body {
color: $finBlue;
padding: 27px;
margin: 12px;
columns: 300px 2;
}
Let us restart watch and save the file.
Let us see what the output will be in the folder heiheiru/app/temp/styles/style.css
$finBlue: #002f6c;
body {
color: #002f6c;
padding: 27px;
margin: 12px;
-moz-columns: 300px 2;
columns: 300px 2;
}
As you can see, the value from the variable was successfully obtained and there is no code unrelated to CSS
in the output - such a file can be safely uploaded to hosting.
Which hosting to choose - read in my article
Choosing hosting for a site
Nested CSS tags (nested css)
For the convenience of developers many plugins have been created that allow
making nested tags, for example create a class and right inside {write the properties of different elements}
In PostCSS the postcss-nested plugin is responsible for this
$ npm install postcss-nested --save-dev
npm WARN heihei@1.0.0 No description
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for
fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
+ postcss-nested@4.1.2
added 5 packages from 6 contributors and audited 10659 packages in 12.936s
found 0 vulnerabilities
Let us add to gulpfile.js
nested = require('postcss-nested');
.pipe(postcss([cssvars, nested, autoprefixer]))
And to heiheiru/app/assets/styles/style.css let us add
.box {
a {
display: block;
padding: 10px;
}
}
This is not valid CSS, but after PostCSS processing it will turn into
.box a {
display: block;
padding: 10px;
}
Import of CSS files
During site development it is convenient to have small separate files for each block.
On the other hand, on hosting it is better to have one style.css file, so that the web server makes fewer
requests to files and the loading time decreases.
postcss-import can include several files into one
$ npm install postcss-import --save-dev
npm WARN heihei@1.0.0 No description
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
+ postcss-import@12.0.1
added 3 packages from 2 contributors and audited 10676 packages in 8.49s
found 0 vulnerabilities
Let us add to gulpfile.js
cssImport = require('postcss-import');
and
.pipe(postcss([cssImport, cssvars, nested, autoprefixer]))
cssImport must be placed at the very beginning of the pipe, so that PostCSS first assembles all modules, and only then starts processing.
To maintain order in the files let us create in the folder heiheiru/app/assets/styles
a subfolder modules.
Let us place the file _topmenu.css there
In the file heiheiru/app/assets/styles/style.css let us write
@import "modules/_topmenu";
Mixins
Mixins are needed for the convenience of developing responsive sites. You can do without them and simply write everywhere
@media screen and (max-width: 360px) and (min-width: 310px)
But with mixins it seems simpler to me. You can try it yourself and compare.
npm install postcss-mixins --save-dev
npm WARN heihei@1.0.0 No description
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
+ postcss-mixins@6.2.2
added 20 packages from 45 contributors and audited 12743 packages in 19.791s
found 0 vulnerabilities
Let us add a new variable
const mixins = require('postcss-mixins');
And add postcss mixins to the pipe
function css() {
console.log('MY_LOG: css function is running');
return src('./app/assets/styles/style.css', {base: './app/assets/styles'})
.pipe( sourcemaps.init() )
.pipe(postcss([cssImport, mixins, nested,autoprefixer,cssvars,cssnano]))
.on('error', function(errorInfo){
console.log("MY_LOG: postcss Failed");
console.log(errorInfo.toString());
this.emit('end'); })
.pipe( sourcemaps.write('.') )
.pipe(gulp.dest('./dist'))
.pipe(gulp.dest('./preFtp/css'));
};
exports.css = css;
Let us create a separate file _mixins.css and do not forget to import it into style.css
@import "base/_mixins";
Let us decide how many width ranges are needed. If you have already made responsive sites, then you know
how many each site needs. The media syntax is the same as in css
Do not forget to insert, inside each media query, @mixin-content;
@define-mixin atSmall {
@media (min-width: 500px) {
@mixin-content;
}
}
@define-mixin atMedium {
@media (min-width: 501px) and (max-width:1000px){
@mixin-content;
}
}
@define-mixin atLarge {
@media (min-width: 1001px) and (max-width:1840px){
@mixin-content;
}
}
@define-mixin atXL {
@media (min-width: 1841px) {
@mixin-content;
}
}
This example uses the Mobile First approach, that is, by default the styles will be for a mobile phone.
Video about PostCSS
Errors
No PostCSS Config found in
Most likely this error appeared as a result of using Postcss with Gulp without sourcemaps
For example there was such code:
gulp.task('serve', function() {
gulp.watch("./app/**/*.css", series(css))
console.log('MY_LOG: serve function is running');
});
function css() {
console.log('MY_LOG: css function is running');
return gulp.src('./app/assets/**/*.css')
.pipe(postcss())
.pipe(gulp.dest('./dest'));
};
exports.css = css;
And in the specification for Postcss it says that when used with Gulp you also need to add sourcemaps. Read the specification
Therefore the code should look something like this:
const sourcemaps = require('gulp-sourcemaps');
function css() {
console.log('MY_LOG: css function is running');
return gulp.src('./app/assets/**/*.css', {base: './app/assets'})
.pipe( sourcemaps.init() )
.pipe(postcss([cssImport, nested,cssvars,autoprefixer ]))
.pipe( sourcemaps.write('.') )
.pipe(gulp.dest('./dest'));
};
exports.css = css;
Article author: Andrei Olegovich