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.
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!
Answer is: css is the result of fs.readFile()
.
Silly mistake on my part. I tried to use the function that they show in the docs, and returned the result of it back to being handled by the file server before the postcss()
function (async) had completed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.