Node.js + Express.js. How to RENDER less css?

依然范特西╮ 提交于 2019-11-29 21:04:30

Gosh, that stuff is very inconsistent in how the paths work, however I found out how you can get it to work.

The first problem is with your paths, both compiler and staticProvider, compiler needs to use /public and is will hook into all requests below that. If you don't do that, the compiler will try to use a path like /public/stylo/stylo.

The second problem lies with the @import in main.less file and the fact that less compiler is stupid and does not handle relative imports.

Using @import "/public/stylo/goodies.css"; in your main.less will make it work.

Filed a Bug for the relative path issue with less:
https://github.com/cloudhead/less.js/issues/issue/177

If you want to minify the outputted css, I found that the built in compiler (from the connect module) was missing the compress option. So rather than writing my own middleware compiler for it. I overwrote the connect less compiler in my app.

var express = require('express');
var app = express.createServer();
var less;

express.compiler.compilers.less.compile = function (str, fn) {
    if (!less) less = require("less");                                                      
    try {
        less.render(str, { compress : true }, fn);
    } catch (err) {
        fn(err);
    }
};

app.use(express.compiler({ src: publicdir, enable: ['less'] }));

The problem is that the compiler only compiles the file if its mtime is changed.

Lets say you have:

// A.less
@import "B.css";

and

// B.less
body {
  background: #f00;
}

I now I modify B.less, A will not be recompiled!

I have a pull request waiting since months, you can use my fork compiler instead of the master one.

https://github.com/senchalabs/connect/pull/167

I've published a package on GitHub called node-kickstart-example which uses a handy pre-configured express with enabled jade template rendering and less stylesheet processing. Use npm to install kickstart, place your jade templates in views/ and your less files in assets/styles/ and your good to go…

Matt Sain's solution for generating compressed css files with less and express is in included in kickstart.

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