在我的package.json中,我正在运行一个一次只能处理一个文件的节点模块(我没有写它)。例如:


 cleancss somefile.css -o somefile-min.css


&#xA ; 我希望能够做类似的事情:


 printfilelist -dir / public / css -files * .css | cleancss {filepath}。{fileext} -o {filename} -min.css



 有没有办法做到这一点?

答案 0 :(得分:1)
我最近遇到了跨多个文件运行cleancss
的类似要求。最终选择了类似于评论中讨论的解决方案,即使用带有实用程序node.js
的{{3}}。
"scripts": {
"cleancss": "glob \"public/css/**/*.css\" | node .scripts/cleancss.js"
},
请注意clean-css-api的初始使用(添加到package.json
),以便在将其汇总到cleancss.js
之前获取路径。
utitlity节点脚本如下(虽然相当简陋!):
#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var readline = require('readline');
var CleanCSS = require('clean-css');
var mkdirp = require('mkdirp');
var rl = readline.createInterface({
input: process.stdin,
output: null,
terminal: false
});
var options = {
// ... https://www.npmjs.com/package/clean-css#constructor-options
// ... https://www.npmjs.com/package/clean-css#formatting-options
};
function saveFile(outputPath, minified) {
fs.writeFile(outputPath, minified, function(err) {
if (err) {
return console.log(err);
}
});
}
function pathParts(srcPath) {
var ext = path.extname(srcPath),
name = path.basename(srcPath, ext),
dirPath = path.dirname(srcPath),
pathParts = dirPath.split(path.sep),
pathNoRoot;
pathParts.shift();
pathNoRoot = pathParts.join(path.sep);
return {
ext: ext,
name: name,
pathNoRoot: pathNoRoot
};
}
function minify(srcPath, outputPath) {
var output = new CleanCSS(options).minify([srcPath]);
saveFile(outputPath, output.styles);
}
function processPath(srcPath) {
var outDir = process.env.npm_package_config_css_outdir || path.dirname(srcPath),
p = pathParts(srcPath),
newName = p.name + '.min' + p.ext,
mkDirPath,
outputPath;
if (process.env.npm_package_config_css_outdir) {
mkDirPath = outDir + path.sep + p.pathNoRoot + path.sep;
mkdirp(mkDirPath, function() {
outputPath = mkDirPath + newName;
minify(srcPath, outputPath);
});
} else {
outputPath = outDir + path.sep + newName;
minify(srcPath, outputPath);
}
}
rl.on('line', function(srcPath) {
processPath(srcPath);
});
.min.css
文件将输出到与.css
源文件相同的路径。package.json
中的cli-glob对象。以下示例将所有.css.min
输出到./dist/
路径:"config": {
"css_outdir": "./dist"
},
"scripts": {
"cleancss": "glob \"public/css/**/*.css\" | node .scripts/cleancss.js"
},
cleancss.js
在使用.css
时利用config复制/镜像目标文件夹中的config.css_outdir
源路径/子文件夹。