davidguttman / cssify

Simple middleware for Browserify to add css styles to the browser.
122 stars 19 forks source link

Callback to additionally process CSS #48

Closed niksy closed 6 years ago

niksy commented 8 years ago

Any chance of having a callback which will receive raw CSS and return processed CSS? That way you can apply additional transformations like PostCSS plugins.

faergeek commented 8 years ago

I would suggest you to use browserify transforms for additional pre/post-processing. I'm not sure but seems like https://github.com/zoubin/browserify-postcss is what you need. It's actually pretty easy to write your own though.

niksy commented 8 years ago

Hm, but isn’t the content of the processed require statement already transformed via cssify if I put another transform in the chain of transforms for Browserify instance? What I’m looking for is one entry point for processing require statements with .css extension.

faergeek commented 8 years ago

You should put your transform before cssify, not after, and it should just transform CSS. With code like this you can transform CSS in any way you like:

var Transform = require('stream').Transform;
var postcss = require('postcss');
var autoprefixer = require('autoprefixer');

var cssRE = /\.css$/;

var passThrough = {
  write: function(buf, enc, cb) {
    this.push(buf);
    cb();
  }
};

var processCss = {
  write: function(buf, enc, cb) {
    this.buffers = this.buffers || [];
    this.buffers.push(buf);
    cb();
  },

  flush: function(cb) {
    var push = this.push.bind(this);

    postcss([autoprefixer])
      .process(Buffer.concat(this.buffers).toString('utf-8'))
      .then(function(result) {
        push(result.css);
        cb();
      })
      .catch(function(err) {
        cb(err);
      })
    ;
  }
};

module.exports = function(file, opts) {
  if (!cssRE.test(file)) return new Transform(passThrough);

  return new Transform(processCss);
};

Sorry, I can't provide better solution to that issue right now. But I'm going to write and publish PostCSS transform ASAP. Please tell me which transformations you're going to make if it's not just PostCSS.

niksy commented 8 years ago

Yeah, this looks right. I think PostCSS is quite good enough, it really should be doing one thing: expect input CSS and produce transformed output CSS. Everything else should be another transform.