Use autoprefixer with strings or streams

259 views Asked by At

I use babel plugin to transform sass imports into string with Angular2 in order to inline styles right into component code during gulp build. I need to also use autoprefixer, but I wasn't able to make solutions I found working, basically, here is the part of code that renders sass to css:

var css = sass.renderSync({
   'data': scss,
   'outputStyle': 'compressed',
   'includePaths': [dir]
}).css.toString();

I tried to find autoprefixer plugin working with strings and tried transforming result of renderSync to stream and using plugins for streams, but no luck. I don't want to use a workaround writing css to temp file and autoprefixing from there, so maybe there is some solution that I could miss?

1

There are 1 answers

0
Sven Schoenung On BEST ANSWER

autoprefixer is a postcss plugin. That means you have to use it with postcss.

The postcss JavaScript API works by creating a processor that uses the specified plugins. You then pass the CSS string to .process(). This returns a Promise that gives you access to the result CSS.

var postcss = require('postcss');
var autoprefixer = require('autoprefixer');

var css = 'display: flex';

postcss([autoprefixer({ browsers: ['> 1%', 'last 2 versions'] })])      
  .process(css)
  .then(function(result) {
    console.log(result.css);
  })

Output:

display: -webkit-box;display: -ms-flexbox;display: flex