Skip to content

Instantly share code, notes, and snippets.

@yuezk
Created March 5, 2016 14:07
Show Gist options
  • Save yuezk/483627ca86c08776be30 to your computer and use it in GitHub Desktop.
Save yuezk/483627ca86c08776be30 to your computer and use it in GitHub Desktop.
Transform CSS files use PostCSS
var through = require('through2');
var postcss = require('postcss');
function postcssTransform(filename, options) {
if (!/\.css$/.test(filename)) {
return through();
}
if (typeof options === 'undefined' || options === null) {
options = {};
}
var processors = Array.isArray(options.processors) ? options.processors : [];
var chunks = [];
function transform(chunk, enc, next) {
chunks.push(chunk);
next();
}
function flush(callback) {
var stream = this;
var source = Buffer.concat(chunks).toString();
postcss(processors)
.process(source, { from: filename })
.then(function (result) {
var moduleBody = 'module.exports = ' + JSON.stringify(result.css) + ';';
stream.push(moduleBody);
callback();
}, function (err) {
callback(err);
});
}
return through(transform, flush);
}
// Usage
browserify('path/to/app.js')
.transform(postcssTransform, {
processors: [
url({ url: 'inline' }),
cssnano({ safe: true })
]
})
.bundle();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment