构建基于 NodeJS 的 LESS.js 预编译 CSS 服务

来源:互联网 发布:理解大数据 编辑:程序博客网 时间:2024/04/30 06:18

我们在项目中使用 Less.js 的预编译 css 技术。Less 最终编译的代码是 css,也就是 *.less 输出 *.css 的工作,围绕这项过程的方式方法多种多样,有的是导入 less.js 到页面编译 less(客户端执行),有的是透过构建工具如 Grunt、Glup 生成。客户端执行比较耗时而且也有浏览器兼容的问题,故不推荐;构建工具比较流行于前端社区,如果放在 JEE 项目中似乎太重了,不便于 Javaer 学习跟使用。我们想,既然 less 是 js 编写的编译器,其官方也有提供跟 nodejs 对接 npm 包,那干脆通过 nodejs 搭建一个 web 服务器,接收到请求就返回编译好 css 便完事。

页面上通过 link 标签导入 node 运行着的服务,返回由参数所指定的 less 文件-->css 文件。如下例子如是:

<link rel="Stylesheet" type="text/css" href="http://192.168.1.92/lessService/?isdebug=true&ns=C:/work/eclipse/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/yuetv_wap/asset/less&lessFile=C:/work/eclipse/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/yuetv_wap/asset/less/yuetv_wap.less&picPath=http://localhost:8080/yuetv_wap/asset/images/1/&MainDomain=http://192.168.1.92:8080/yuetv_wap" />

其中 url 如:http://192.168.1.92/lessService/?isdebug=true&ns=C:/work/eclipse/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/yuetv_wap/asset/less&lessFile=C:/work/eclipse/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/yuetv_wap/asset/less/yuetv_wap.less&picPath=http://localhost:8080/yuetv_wap/asset/images/1/&MainDomain=http://192.168.1.92:8080/yuetv_wap

请求的参数应按如下表传参:

参数名是否必传含义lessFileyLESS 文件位置,就是要解析的 LESS 文件名全称nsn参数 ns =namespace 为命名空间之目录名,LESS 会在此目录下自动加入 LESS 而无须加上 目录前缀。通常为项目的 LESS 总目录,该目录下有多个 LESS 文件picPathn参数 picPath 是背景图的所在目录。开发阶段和线上的部署阶段的目录会有所不同isdebugn参数 isDebug = true 为调试阶段,不压缩 css 输出;当 isDebug = false 时候,压缩输出

通过上述介绍大家应该明白这是一种什么思路了。好接着我们需要一个 nodejs 环境,而且安装 less.js NPM 包。NPM 下载:

npm install less (https://www.npmjs.com/package/less)

OR

下载我提供的 js 包,内置了 less.js 包完整依赖。(稍后提供)

光有包不够,真正把 less 服务暴露到 web 还是下面 js 脚本。下载下面 js。

  • http://git.oschina.net/sp42/ajaxjs/blob/master/nodejs/less-parser.js?dir=0&filepath=nodejs%2Fless-parser.js
  • http://git.oschina.net/sp42/ajaxjs/blob/master/nodejs/lib/step.js?dir=0&filepath=nodejs%2Flib%2Fstep.js
  • http://git.oschina.net/sp42/ajaxjs/blob/master/nodejs/lib/webserver-utils.js?dir=0&filepath=nodejs%2Flib%2Fwebserver-utils.js

首先我们要让 nodejs 跑起 web 服务来,这是 nodejs 强项,仅次于 hello world 用法:

const HTTP = require('http'), less = require('less'), fs = require('fs'), Step = require('./lib/step'), webUtils = require('./lib/webserver-utils');const port = 80, base_less_folder = 'c:/project/ajaxjs/less',server = HTTP.createServer((req, res) => {init(req, res);});server.listen(port, null, () => {var host = '';console.log(`Image Server running at http://${host}:${port}/`);});

这里是 80 端口,需要的话就修改吧。还有个 base_less_folder 配置你也可以修改,是关于 less 读取的目录,也就是上述 ns 参数。当前默认有一个,然而可以通过 url 参数陆续添加。

真正处理转换的是 init 函数:

init = function (request, response) {console.log('Current Less.js vresion:' + less.version.join('.'));var _req = webUtils.url2json(request.url),lessFile = _req.lessFile,ns = _req.ns; // 读取 url 的命名空间if (!lessFile) return webUtils.show500error(response, '未发行对应的样式文件!');// 指定包空间var ns_arr = [            base_less_folder    ];ns && ns_arr.push(ns);// 背景图的路径按 CSS 为基准。但因为 CSS 处于 Node 服务器上,所以要指定到 Tomcat 上才行。var assetFilePath = '@assetFilePath: "http://localhost:8080/sport/asset/images";\n';var assetFilePath = '@assetFilePath: "' + _req.picPath + '";\n';Step(function () {console.log('请求 LESS 命名空间:' + lessFile.split('/').pop());fs.readFile(lessFile, "utf8", this);}, function (err, lessFile) {if (err) return webUtils.show500error(response, '未发行对应的样式文件!原因:' + err.toString());var isDebug = _req.isdebug; // 是否压缩样式 try {less.render(assetFilePath + lessFile, {paths: ns_arr,compress: (!isDebug || isDebug == 'false')}, this);} catch (e) {return webUtils.show500error(response, 'LESS 解析 less 失败,请检查 LESS 文件是否写错!原因:' + e);}}, function (err, tree) {if (err) return webUtils.show500error(response, 'LESS 解析 less 失败!原因:' + err);response.writeHead(200, { 'Content-Type': 'text/css; charset=UTF-8' });var isDebug = _req.isdebug; // 是否压缩样式response.end(tree.css);if (!isDebug || isDebug == 'false') {}else if (isDebug == 'true') { }// 总是 localhost/app 后面有一个 app 项目名// deployUsed = deployUsed.replace(/http:\/\/localhost:8080\/\w+/i, _req.MainDomain);// console.log('--------' + tree);console.log('--------' + _req.picPath);var deployUsed = tree.css.replace(new RegExp(_req.picPath, 'g'), '../images');// 保存文件在父级 css 目录下,save to file// toCSS(lessFile.replace(/(.*?\/)(\w+)\.less/, '$1../css/$2.css'), deployUsed);});}

这里使用了 step.js 避免 callback hell 问题和封装了相关 web 的方法。

值得注意的是,这一系列过程都是开发环境用的。如果生成环境就是得 css 读取了。我们的后台会自动识别,如果开发的时候就走 less/node 的,生产环境就 css。

怎么让生产环境读到 css 呢?一个笨方法就是手工 copy 导出的再保存,另外一种方法就是上面脚本 倒数第三行的,自动把得到的 css 保存起来,这样就不用手工拷贝了。

0 0
原创粉丝点击