javascript - 通过 Node 脚本减少 CSS

标签 javascript css node.js less

找到解决方案,请参阅本文底部

Trying to build LESS (less css) using a build script with nodeJS

我正在尝试使用 Node 脚本从 less 构建一个 css 文件,我的文件结构无法更改,如下所示:

/public/css/app.css
/resources/assets/less/xenon.less
/quickSync/02_lessCompiler.js

less 文件的内容有效地包含与 .less 文件本身相同级别及更高级别的其他 less 文件,例如:

// Import Bootstrap Variables & Mixins
@import "bs-less/variables.less";
@import "bs-less/mixins.less";

// LessHat
@import "other-less/lesshat.less";
... etc etc

从上面的链接我尝试了以下操作:

var less = require( 'less' );
var fs = require( 'fs' );
var path = require('path');

var basePath = __dirname + '/..';

var lessPath    = basePath + '/resources/assets/less/xenon.less',
    outputPath  = basePath + '/public/css/app.css';
fs.readFile( lessPath ,function(error,data){
    data = data.toString();
    console.log( error );
    console.log( data );

    less.render(data, function (e, css) {
        console.log( e );
        console.log( css );
        fs.writeFile( outputPath, css, function(err){
            if( err ){
                console.log(err );
            }
            console.log('done');
        });
    });
});

上述解决方案的控制台输出是:

null
// Import Bootstrap Variables & Mixins
@import "bs-less/variables.less";
@import "bs-less/mixins.less";

// LessHat
@import "other-less/lesshat.less";

// Xenon Basic UI
@import "xenon-core.less";

// Forms
@import "xenon-forms.less";

// Xenon Extra Components
@import "xenon-components.less";

// Xenon Skins
@import "xenon-skins.less";
{ [Error: 'xenon-skins.less' wasn't found. Tried - xenon-skins.less,xenon-skins.less]
  type: 'File',
  filename: 'input',
  index: 311,
  line: 18,
  callLine: NaN,
  callExtract: undefined,
  column: 0,
  extract: [ '// Xenon Skins', '@import "xenon-skins.less";', undefined ],
  message: '\'xenon-skins.less\' wasn\'t found. Tried - xenon-skins.less,xenon-skins.less',
  stack: undefined }
undefined
done

但是,输出文件只是读取

undefined

undefined

然后我找到了这个人的博客:http://onedayitwillmake.com/blog/2013/03/compiling-less-from-a-node-js-script/并尝试了以下方法:

var less = require( 'less' );
var fs = require( 'fs' );
var path = require('path');
var lessPath    = basePath + '/resources/assets/less/xenon.less',
    outputPath  = basePath + '/public/css/app.css';

//ensure directory exists
var ensureDirectory = function (filepath) {
    var dir = path.dirname(filepath);
    var existsSync = fs.existsSync || path.existsSync;
    if (!existsSync(dir)) {
        fs.mkdirSync(dir);
    }
};

fs.readFile( lessPath, function(error, data){

        var dataString = data.toString();


        var options = {
            paths         : [basePath + '/resources/assets/less'],  // .less file search paths
            outputDir     : basePath + '/public/css',               // output directory, note the '/'
            optimization  : 1,                                      // optimization level, higher is better but more volatile - 1 is a good value
            filename      : "xenon.less",                              // root .less file
            compress      : false,                                  // compress?
            yuicompress   : false                                   // use YUI compressor?
        };

        console.log( options );

        options.outputDir = path.resolve( process.cwd(), options.outputDir) + "/";
        ensureDirectory( options.outputDir );

        var parser = new less.Parser(options);
        console.log( 'parsing' );
        parser.parse( dataString, function ( error, cssTree ) {
            if ( error ) {
                console.log( 'Error compiling less:' );
                console.log( error );
                return false;
            }

            // Create the CSS from the cssTree
            var cssString = cssTree.toCSS({
                compress: options.compress,
                yuicompress: options.yuicompress
            });

            fs.writeFile(outputPath, cssString, function (err) {
                logTime('Compiled less: ' + outputPath);
                //run the mai passed callback function
                callback();
            });
        });
    });

但是输出是一个错误:

D:\myproject\node_modules\less\lib\less\parser\parser.js:117
            imports.contents[fileInfo.filename] = str;
                   ^

TypeError: Cannot read property 'contents' of undefined
    at Object.Parser.parse (D:\myproject\node_modules\less\lib\less\parser\parser.js:117:20)
    at D:\myproject\quickSync\02_lessCompiler.js:51:16
    at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:380:3)

这让我发疯,用 sass 你就可以了:

require('node-sass').render({
        file: scssPath,
        outFile: outputPath,
        outputStyle: 'expanded',
        sourceComments: true
    }, function( err, result ){
  //write result to disk.
});

使用无 Node 编译器构建 css 最简单的方法是什么?

解决方案:

 fs.readFile( lessPath ,function(error,data){
        data = data.toString();

        less.render(data, {
            paths: [ basePath + '/resources/assets/less/' ]
        },function (e, css) {
            fs.writeFile( outputPath, css.css, function(err){
                if( err ){
                    console.log(err );
                }
                console.log('done');
            });
        });
    });

最佳答案

第一个作品在这里,也许你应该

console.log(error)

在readFile回调中,很可能是你的路径错误,导致文件打不开。

关于javascript - 通过 Node 脚本减少 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35061409/

相关文章:

javascript - 使用javascript拖动多个div

javascript - 在 react native 中从 sqlite 存储返回查询结果时未定义

node.js - 如何使用 Sequelize 更新我的购物车数据库中的商品数量(如果它已经存在)或如果不存在则创建它?

node.js - 将您的电子邮件地址放入 npm 模块的 package.json 中是否安全?

Node.js/了解 ReadStream.pipe 是否正在传输数据

javascript - 读/写 Windows 图像标签(关键字)

javascript - 将 image/jpeg 作为 arraybuffer 或 blob 返回

javascript - 用 JavaScript 和 P5 创建游戏 - 几个基本问​​题

html - 重新排列同级 DIVS

html - 中间div和右div在里面的DIV