cssnode.jsautoprefixerpostcss

Use autoprefixer synchronously


I want to use autoprefixer in my node application to compile css. For my specific needs, I want to call autoprefixer without callback or promise.

Just plain:

var result = autoprefixer.process(css);

or

var result = myPrefixerWrap(css);

I am fighting with this for a while, can you help me please?

ps: I already tried postcss-js, but it result an json object for react use, and not pure css. For example {borderRadius:"5px"}

var prefixer    = postcssJs.sync([ autoprefixer ]);
var cssCompiled = postcss.parse(css);
var cssObject   = postcssJS.objectify(cssCompiled);
var autoResult  = prefixer(cssObject);

Solution

  • PostCSS has an API for synchronously getting the results of Processor#process (process().css, aliased as toString()), which will work as long as all of the PostCSS plugins being used are synchronous (like Autoprefixer). The code to do that is as simple as:

    var postcss = require('postcss'); // import postcss from 'posts';
    var autoprefixer = require('autoprefixer'); // import autoprefixer from 'autoprefixer';
    postcss([autoprefixer]).process(styleString).css;
    

    Note: I had issues with using postcss-js in Webpack, so for those who see errors like:

    Module parse failed: /path/to/node_modules/autoprefixer/node_modules/caniuse-db/features-json/css-regions.json Line 2: Unexpected token :
    You may need an appropriate loader to handle this file type.
    

    Or:

    ERROR in ./~/autoprefixer/~/browserslist/index.js
    Module not found: Error: Cannot resolve module 'fs' in /path/to/node_modules/autoprefixer/node_modules/browserslist
     @ ./~/autoprefixer/~/browserslist/index.js 3:14-27
    

    Check out the Troubleshooting section of the postcss-js GitHub readme to find out what you need to add to your Webpack config to get it working.