我想我已经解决了你的问题。
您想将文件读入一个名为的变量css
并传递css
给process()
. 问题在于您使用哪种方法来读取文件的内容。
目前,您使用fs.readFile
的是异步的。您正在使用它,就好像它是同步的一样。因此,您有两种选择:
使用fs.readFile
它打算使用的方式,又名:异步:
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 );
});
});
}
如果你决定使用它,学习promises可能是个好主意,它可以清理异步代码。
或者代替fs.readFile
,您可以使用fs.readFileSync
which 将同步读取文件。根据您的文件有多大,这不是最好的主意。
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 );
});
}
希望这可以帮助!