Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Autoprefixer with Node.js

According to the official documentation, this is simple:

Usage:

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

postcss([ autoprefixer ]).process(css).then(function (result) {
    result.warnings().forEach(function (warn) {
        console.warn(warn.toString());
    });
    console.log(result.css);
});

However, I'm confused as to what exactly I do to establish the object css to use with process(). I tried using the result of fs.readfile() but it doesn't seem to be working. My server module is fairly large, and it might be better to leave out code here. I really just simply need to know how to create css for the process function.


1 Answers

I think I've solved your issue.

You want to read a file into a variable called css and pass css to process(). The problem lies in which method you use to read the contents of the file.

Currently, you use fs.readFile which is asynchronous. You are using it as if it were synchronous. Therefore, you have two options:

Use fs.readFile the way it is intended to be used, aka: asynchronously:

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

function processCSS(file, cb){

  fs.readFile(file, {encoding: String}, function (err, css) { 
      if (err) throw err;
      postcss([ autoprefixer ]).process(css).then(function (result) {
          result.warnings().forEach(function (warn) {
              console.warn(warn.toString());
          });
          console.log(result.css);
          cb( result.css );
      });
  });

}

If you decide to use this, it might be a good idea to learn about promises, which can clean up async code.

Or instead of fs.readFile, you can use fs.readFileSync which will read the file synchronously. Depending on how large your file is, this isn't the best idea.

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

function processCSS(file, cb){

  var css = fs.readFileSync(file, {encoding: String});
  postcss([ autoprefixer ]).process(css).then(function (result) {
      result.warnings().forEach(function (warn) {
          console.warn(warn.toString());
      });
      console.log(result.css);
      cb( result.css );
  });

}

Hope this helps!

like image 196
theideasmith Avatar answered May 27 '26 02:05

theideasmith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!