关键词:dojo ant custom_rhino.jar rhino javascript混淆
三、使用dojo compressor + ant
dojo是个非常经典的开源web开发框架,值得学习。dojo的混淆是基于custom_rhino.jar,custom_rhino.jar是基于mozilla的java脚本解析器rhino,jdk6.0就使用rhino做脚本解析。
单个文件的压缩可以这样做,用命令行进入custom_rhino.jar目录执行下面的命令 java -jar custom_rhino.jar -c infile.js > outfile.js
如果项目中有很多js文件,这样就很不方便了,可以写个ant脚本,ant很好很强大。
目录结构如下:
下面贴下我一个同事写的扩展:
builde.xml
<?xml version="1.0"?> <project name="jscompress" basedir="." default="reload"> <property name="js.dir" value="js"/> <property name="lib.dir" value="lib"/> <property name="build.dir" value="build"/> <path id="master-classpath"> <fileset dir="${lib.dir}"> <include name="*.jar"/> </fileset> </path> <target name="prepare"> <mkdir dir="${build.dir}"/> </target> <target name="build" depends="prepare"> <copy todir="${build.dir}"> <fileset dir="${js.dir}"> <include name="**"/> </fileset> </copy> </target> <!--=========added for compress js=================--> <target name="compress" depends="build"> <java classname="org.mozilla.javascript.tools.shell.Main" fork="true"> <arg line="-f garfield_compress.js"/> <classpath> <path refid="master-classpath"/> </classpath> </java> </target> </project>
js脚本
load("buildUtil.js"); // //mycontents=buildUtil.readFile("infile.js","utf-8") //filecontents=buildUtil.optimizeJs("infile.js",mycontents,"/*copyright*/",true) //buildUtil.saveUtf8File("kaka.js",filecontents.replace(//n/g,"")) // var js_src_path=java.io.File("js"); var compress_file_callback=function(jsfile){ print( jsfile); var myfilename=jsfile.getName(); var now_filename=jsfile.getPath(); if(myfilename.match(/.js$/)){ var mycontents=buildUtil.readFile(jsfile.getPath()); mycontents=buildUtil.optimizeJs(now_filename,mycontents,"",true); mycontents=mycontents.replace(//n/g,""); buildUtil.saveUtf8File(now_filename+".compressed",mycontents); jsfile.renameTo(new java.io.File(now_filename+".uncompressed")); java.io.File(now_filename+".compressed").renameTo(new java.io.File(now_filename)); } } var walk_directory=function(dir){ if(dir.isDirectory()&&dir.getName().match(/^dojo/)==null){ var file_list=dir.listFiles() for(var i=0;i<file_list.length;i++){ var myfile=file_list[i] if(myfile.isFile()){ compress_file_callback(myfile) }else{ walk_directory(myfile) } } } } walk_directory(js_src_path);
其中用到了dojo的几个辅助方法,需要可以留言找我。代码比较多我就不贴了。扩展后对于代码发布很方便。