PostCSS 4.1 brings async plugins support and messages API.
Asynchronous Plugins
PostCSS 4.1 allows plugins to operate asynchronously, by returning a Promise.
module.exports = postcss.plugin('postcss-read', function (opt) {
return function (css) {
return new Promise(function (resolve, reject) {
fs.readFile(opt.file, function (err, content) {
if ( err ) {
reject(err);
} else {
css.append(content);
resolve();
}
});
});
};
});
Note, that PostCSS still runs plugins one-by-one to avoid conflicts.
Messages API
Result
instance now has messages
array for plugin communications.
Main usage of this messages API is a warnings with Result#warn()
and Result#warnings()
shortcuts:
var plugin = postcss.plugin('postcss-important-linter', function () {
return function (css, result) {
css.eachDecl(function (decl) {
if ( decl.important ) {
result.warn('Try to avoid !important', { node: decl });
}
});
}
});
postcss([plugin]).process(css).then(function (result) {
result.warnings().forEach(function (msg) {
console.warn(msg.toString());
});
});
With postcss-messages you can see all plugins warnings.
Plugin API
4.1 release contains postcss.plugin()
function:
var postcss = require('postcss');
module.exports = postcss.plugin('postcss-plugin-name', function (opts) {
return function (css) {
// Process css
};
});
It creates a plugin with a standard API:
plugin.postcssPlugin //=> "postcss-plugin-name"
plugin.postcssVersion //=> "4.1.0"
postcss([ plugin ]) // with default options
postcss([ plugin({ prop: 'color' }) ]) // with options
Also node.error()
now accepts plugin
option:
if ( !variables[name] ) {
throw decl.error('Unknown variable ' + name, { plugin: 'postcss-vars' });
}
Guidelines
As PostCSS grows, it is time to take care of its ecosystem.
As first step we made the Guidelines for PostCSS runners, like gulp-postcss or postcss-cli.
The guidelines for plugin developers will be published next month. Stay tuned with @PostCSS.
Other Changes
- Insert nodes by CSS string.
- Show version warning message on error from an outdated plugin.
- Send
Result
instance to plugins as the second argument. - Add
CssSyntaxError#showSourceCode()
. - Add
postcss.list
andpostcss.vendor
aliases. - Parse wrong closing bracket.
- Add
Processor#version
. - Parse
!important
statement with spaces and comments inside (by @ben-eb). - Throw an error on declaration without
prop
orvalue
(by @philip-peterson). - Fix source map mappings position.
- Add indexed source map support.
- Always set
error.generated
. - Clean all source map annotation comments.