之前是想通过nginx_lua模块简单地对js进行压缩,但是在第一步删除js的单行注释就难倒了我,通过正则我想是处理不了的,只好去搜索有哪些好用的js压缩软件,找到了UglifyJS这个基于node.js的js压缩引擎。这个工具可以在linux命令行使用,也提供了NodeJS的API。我们这里是通过lua的os.popen直接调用uglifyjs命令来压缩js。
一、Node.js安装
- cd /tmp
- wget http://nodejs.org/dist/v0.8.12/node-v0.8.12.tar.gz
- tar xzf node-v0.8.12.tar.gz
- cd node-v0.8.12
- ./configure && make && make install
注意:需要python的版本为2.6以上,否则会出现错误:
- File "./configure", line 330
- o['default_configuration'] = 'Debug' if options.debug else 'Release'
- ^
- SyntaxError: invalid syntax
升级python可以参考:https://www.centos.bz/2012/10/linux-python-upgrade/
二、安装UglifyJS
- npm install uglify-js
有可能出现的问题:
1、ImportError: No module named bz2
解决方法:
- yum -y install bzip2 bzip2-devel
- cd /tmp/Python-2.7.3/Modules/zlib
- ./configure && make && make install
- cd ../../
- python setup.py install
三、UglifyJS使用
1、使用命令行
语法:uglifyjs [ options… ] [ filename ]
详细的用法:https://github.com/mishoo/UglifyJS
2、使用node.js http
server.js脚本内容:
- var http = require("http");
- var jsp = require("uglify-js").parser;
- var pro = require("uglify-js").uglify;
- function onRequest(request, response) {
- var postData = "";
- request.setEncoding("utf8");
- request.addListener("data", function(postDataChunk) {
- postData += postDataChunk;
- });
- request.addListener("end", function() {
- var orig_code = postData;
- var ast = jsp.parse(orig_code);
- ast = pro.ast_mangle(ast);
- ast = pro.ast_squeeze(ast);
- var final_code = pro.gen_code(ast);
- response.writeHead(200, {"Content-Type": "text/plain"});
- response.write(final_code);
- response.end();
- });
- }
- http.createServer(onRequest).listen(8888,"127.0.0.1");
- console.log("Server has started.");
执行node server.js即可。