[英]How do I use Autoprefixer with Node.js
根据官方文档,这很简单:
用法:
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()
的结果,但它似乎不起作用。 我的服务器模块相当大,最好在此处省略代码。 我真的只需要知道如何为 process 函数创建css
。
我想我已经解决了你的问题。
你想文件读入一个变量,名为css
,并通过css
来process()
问题在于您使用哪种方法来读取文件内容。
目前,您使用的是异步的fs.readFile
。 您正在使用它,就好像它是同步的一样。 因此,您有两个选择:
以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
同步读取文件。 根据您的文件有多大,这不是最好的主意。
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 );
});
}
希望这可以帮助!
答案是:css是fs.readFile()
的结果。
我犯了一个愚蠢的错误。 我尝试使用他们在文档中显示的函数,并在postcss()
函数(异步)完成之前将其结果返回给文件服务器处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.