Created
March 5, 2016 14:07
-
-
Save yuezk/483627ca86c08776be30 to your computer and use it in GitHub Desktop.
Transform CSS files use PostCSS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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