3

根据官方文档,这很简单:

用法:

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);
});

但是,我很困惑我究竟做了什么来建立css要使用的对象process()。我尝试使用的结果,fs.readfile()但它似乎没有工作。我的服务器模块相当大,在这里省略代码可能会更好。我真的只需要知道如何创建css流程功能。

4

2 回答 2

2

我想我已经解决了你的问题。

您想将文件读入一个名为的变量css并传递cssprocess(). 问题在于您使用哪种方法来读取文件的内容。

目前,您使用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.readFileSyncwhich 将同步读取文件。根据您的文件有多大,这不是最好的主意。

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 );
  });

}

希望这可以帮助!

于 2015-08-07T02:53:00.090 回答
0

答案是:css.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.

于 2015-08-04T04:07:25.913 回答