Combining two .less files in one

倾然丶 夕夏残阳落幕 提交于 2019-12-22 08:54:52

问题


Suppose I have two less files, first.less

.a {
  .b {
    font-size: 13px;
  }
  color: lime;
}

and second.less

@import "first.less";
.a {
  font-family: sans-serif;
}

I would like a way of combining them into one, merging the trees:

.a {
  .b {
    font-size: 13px;
  }
  color: lime;
  font-family: sans-serif;
}

So, something similar as compiling to .css, but keeping the .less structure. Is it possible to do via a command line tool, library or programmatically?


回答1:


What @helderdarocha means, you can write native javascript and run this with node.js. See for instance http://lesscss.org/#using-less-usage-in-code and http://onedayitwillmake.com/blog/2013/03/compiling-less-from-a-node-js-script/

  1. install less with: npm install less (this wil create a node_modules directory)
  2. create your second.less file
  3. create a test.js file, something like:
    var less = require( 'less' );
    var fs = require( 'fs' );
    var parser = new less.Parser();
    fs.readFile( 'second.less', function ( error, data ) {
      var dataString = data.toString();
      parser.parse(dataString, function ( err, tree ) {
        if ( err ) {
          return console.error( err );
        }
        console.log( tree.toCSS() );
      });
    });
  1. now you could run: >> node test.js

To above will output CSS code and not the Less code you want. To get the desired result you should extend the less code with a toLess() function which can be invoked on tree just like toCSS(). I wonder if this is the best way to get your desired result, what your seem to want is some kind of selector merging. Notice that Less don't merge selectors (see: https://github.com/less/less.js/issues/930). Maybe also take a look at http://css2less.cc/ which merge selectors.



来源:https://stackoverflow.com/questions/24205110/combining-two-less-files-in-one

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!