Using LESS with node.js

2019-02-06 17:01发布

问题:

Less is amazing and I want to use to node.js because using less.js is not a good performance. I testing purpos i'm using xamp on windows and I install node.js but where and what i should write.. I install express.js npm install -g express and less npm install -g less

回答1:

If you're using expressjs you can install

npm install less-middleware

and then in your application (app.js)

var lessMiddleware = require('less-middleware');

then you have to tell expressjs to use less-middleware by doing

app.configure(function(){
  //other configuration here...
  app.use(lessMiddleware({
    src      : __dirname + "/public",
    compress : true
  }));
  app.use(express.static(__dirname + '/public'));
});

now in your [appname]/public/stylesheets/custom.less

gets translated into regular css custom.css



回答2:

If you're using express 4.x and less-middleware 0.2.x beta (which is the latest at the moment), the syntax is a bit different.

This is the same:

$ npm install less-middleware

But the middleware has a source and three option parameters:

function(source, options, parserOptions, compilerOptions)

Example:

app.use(require('less-middleware')(
    __dirname + 'public/style/less', // source
    { dest: __dirname + 'public/style/css' }, // options
    {}, // parser
    { compress: 'auto' } // complier
));

app.use(express.static(__dirname + '/public'));

The complier's auto compress is really nice, style.css will result in an uncompressed and style.min.css will give you a compressed file.

For more info you should check out the Migration guide and the source code here: https://github.com/emberfeather/less.js-middleware



标签: node.js less