Trying to build LESS (less css) using a build scri

2019-04-09 00:15发布

问题:

We are using NodeJS to build our project. We have integrated LESS CSS as a part of the project. We are attempting to keep our build clean and would like to be able to call the lessc command (or something comparable) in order to build our LESS files.

The LESS documentation isn't very in depth, but wanted to reach out to the community to find a solution. Google has not be too helpful to me on this topic.

We have a build.sh file, that calls various other build.js files (in respective directories). How can I run LESSC to compile my LESS files?

回答1:

Using node.js

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

fs.readFile('style.less',function(error,data){
    data = data.toString();
    less.render(data, function (e, css) {
        fs.writeFile('style.css', css, function(err){
            console.log('done');
        });
    });
});


回答2:

Few years later ... less@3.9.0 returns output as:

{
  css: 'rendered css',
  imports: ['source.css']
}

Updated code can look like this:

const outputFile = 'style-iso.css';

const data = `.bootstrap-iso {
    @import (less) "style.css"; 
} `;

less.render(data, { strictMath: true }).then(
    output => {
        fs.writeFile(outputFile, output.css, err => {
            if (err) {
                throw err;
            }
            console.log(`${outputFile} saved!`);
        });
    },
    err => {
        console.error(err);
    });

Tip

strictMath: true

is necessary if you want to render bootstrap.css



标签: css node.js less