標籤:
http://www.html-js.com/article/1359
我們在用less時,有時會有很多less塊,一個一個手動編譯很麻煩,使用下面的代碼,可以一次性遞迴編譯 在項目less檔案目錄,建立個js檔案。粘貼代碼如下
var fs = require(‘fs‘),path = require(‘path‘),exec = require(‘child_process‘).exec,sourcePath, targetPath; //擷取命令列中的路徑process.argv.forEach(function (val, index, array) {if (index == 2) { sourcePath = val;}if (index == 3) { targetPath = val;}})var lessc = function (rootPath, targetPath) {//取得當前絕對路徑rootPath = path.resolve(rootPath);//目標路徑絕對路徑targetPath = path.resolve(targetPath);//判斷目錄是否存在fs.exists(rootPath, function (exists) { //路徑存在 if (exists) { //擷取當前路徑下的所有檔案和路徑名 var childArray = fs.readdirSync(rootPath); if (childArray.length) { for (var i = 0; i < childArray.length; i++) { var currentFilePath = path.resolve(rootPath, childArray[i]); var currentTargetPath = path.resolve(targetPath, childArray[i]) //讀取檔案資訊 var stats = fs.statSync(currentFilePath); //若是目錄則遞迴調用 if (stats.isDirectory()) { lessc(currentFilePath, currentTargetPath); } else { //判斷檔案是否為less檔案 if (path.extname(currentFilePath) === ".less") { var newFilePath = path.resolve(targetPath, path.basename(currentFilePath, ‘.less‘) + ".css"); if (!fs.existsSync(targetPath)) { fs.mkdirSync(targetPath); } console.log(newFilePath); exec("lessc -x " + currentFilePath + " > " + newFilePath); } } } } } else { console.log("directory is not exists"); } });}lessc(‘./‘, ‘./css/‘);
然後運行node
node 建立的js檔案
nodejs 批量編譯less 檔案為css