使用UglifyJS压缩javascript代码

之前是想通过nginx_lua模块简单地对js进行压缩,但是在第一步删除js的单行注释就难倒了我,通过正则我想是处理不了的,只好去搜索有哪些好用的js压缩软件,找到了UglifyJS这个基于node.js的js压缩引擎。这个工具可以在linux命令行使用,也提供了NodeJS的API。我们这里是通过lua的os.popen直接调用uglifyjs命令来压缩js。

一、Node.js安装

  1. cd /tmp
  2. wget http://nodejs.org/dist/v0.8.12/node-v0.8.12.tar.gz
  3. tar xzf node-v0.8.12.tar.gz
  4. cd node-v0.8.12
  5. ./configure && make && make install

注意:需要python的版本为2.6以上,否则会出现错误:

  1. File "./configure", line 330
  2.     o['default_configuration'] = 'Debug' if options.debug else 'Release'
  3.                                           ^
  4. SyntaxError: invalid syntax

升级python可以参考:https://www.centos.bz/2012/10/linux-python-upgrade/

二、安装UglifyJS

  1. npm install uglify-js

有可能出现的问题:
1、ImportError: No module named bz2
解决方法:

  1. yum -y install bzip2 bzip2-devel
  2. cd /tmp/Python-2.7.3/Modules/zlib
  3. ./configure && make && make install
  4. cd ../../
  5. python setup.py install

三、UglifyJS使用

1、使用命令行
语法:uglifyjs [ options… ] [ filename ]
详细的用法:https://github.com/mishoo/UglifyJS
2、使用node.js http
server.js脚本内容:

  1. var http = require("http");
  2. var jsp = require("uglify-js").parser;
  3. var pro = require("uglify-js").uglify;
  4. function onRequest(request, response) {
  5.   var postData = "";
  6.   request.setEncoding("utf8");
  7.   request.addListener("data", function(postDataChunk) {
  8.       postData += postDataChunk;
  9.   });
  10.  
  11.   request.addListener("end", function() {
  12.       var orig_code = postData;
  13.       var ast = jsp.parse(orig_code);
  14.       ast = pro.ast_mangle(ast);
  15.       ast = pro.ast_squeeze(ast);
  16.       var final_code = pro.gen_code(ast);
  17.   response.writeHead(200, {"Content-Type": "text/plain"});
  18.   response.write(final_code);
  19.   response.end();
  20.   });
  21. }
  22.  
  23. http.createServer(onRequest).listen(8888,"127.0.0.1");
  24.  
  25. console.log("Server has started.");

执行node server.js即可。

发布于:2019-11-23 00:36:09