美文网首页
ant+yuicompressor压缩js/css

ant+yuicompressor压缩js/css

作者: yuhan_sining | 来源:发表于2019-11-16 11:23 被阅读0次

ant+yuicompressor在前端部署和服务器发布中用处极大。我在项目中用到的是ant+yuicompressor,ant可以压缩CSS,压缩javascript,并可以传输信息和远程服务器发布!
目前yuicompressor最新版本为yuicompressor-2.4.8.jar,请使用该版本的jar。因为我使用2.4.7版本后,出现了混淆后的js代码替换环境后使用有问题,而使用2.4.8版本混淆出来的js代码替换环境后则正常。
下载地址:yuicompressor-2.4.8.jar

一、在github上查看yuicompressor的源码

https://github.com/yui/yuicompressor

二、在官网上查看yuicompressor的使用说明

http://yui.github.io/yuicompressor/
通用参数:
-h, –help 显示帮助信息
–type <js|css> 指定输入文件的文件类型
–charset <charset> 指定读取输入文件使用的编码
–line-break <column> 在指定的列后插入一个 line-bread 符号
-v, –verbose 显示info和warn级别的信息
-o <file> 指定输出文件。默认输出是控制台。

JavaScript专用参数:
–nomunge 只压缩, 不对局部变量进行混淆。
–preserve-semi 保留所有的分号。
–disable-optimizations 禁止优化。

详情如下:

java -jar yuicompressor-x.y.z.jar
Usage: java -jar yuicompressor-x.y.z.jar [options] [input file]

  Global Options
    -h, --help                Displays this information
    --type <js|css>           Specifies the type of the input file
    --charset <charset>       Read the input file using <charset>
    --line-break <column>     Insert a line break after the specified column number
    -v, --verbose             Display informational messages and warnings
    -o <file>                 Place the output into <file> or a file pattern.
                              Defaults to stdout.

  JavaScript Options
    --nomunge                 Minify only, do not obfuscate
    --preserve-semi           Preserve all semicolons
    --disable-optimizations   Disable all micro optimizations

GLOBAL OPTIONS

  -h, --help
      Prints help on how to use the YUI Compressor

  --line-break
      Some source control tools don't like files containing lines longer than,
      say 8000 characters. The linebreak option is used in that case to split
      long lines after a specific column. It can also be used to make the code
      more readable, easier to debug (especially with the MS Script Debugger)
      Specify 0 to get a line break after each semi-colon in JavaScript, and
      after each rule in CSS.

  --type js|css
      The type of compressor (JavaScript or CSS) is chosen based on the
      extension of the input file name (.js or .css) This option is required
      if no input file has been specified. Otherwise, this option is only
      required if the input file extension is neither 'js' nor 'css'.

  --charset character-set
      If a supported character set is specified, the YUI Compressor will use it
      to read the input file. Otherwise, it will assume that the platform's
      default character set is being used. The output file is encoded using
      the same character set.

  -o outfile

      Place output in file outfile. If not specified, the YUI Compressor will
      default to the standard output, which you can redirect to a file.
      Supports a filter syntax for expressing the output pattern when there are
      multiple input files.  ex:
          java -jar yuicompressor.jar -o '.css$:-min.css' *.css
      ... will minify all .css files and save them as -min.css

  -v, --verbose
      Display informational messages and warnings.

JAVASCRIPT ONLY OPTIONS

  --nomunge
      Minify only. Do not obfuscate local symbols.

  --preserve-semi
      Preserve unnecessary semicolons (such as right before a '}') This option
      is useful when compressed code has to be run through JSLint (which is the
      case of YUI for example)

  --disable-optimizations
      Disable all the built-in micro optimizations.

可以使用java命令调用方式,例如:

java -jar yuicompressor-x.y.z.jar myfile.js -o myfile-min.js
java -jar yuicompressor-x.y.z.jar myfile.js -o myfile-min.js --charset utf-8

三、在ant中配置yuicompressor进行js和css的压缩步骤

1、配置yuicompressor包的版本号

打开ivy-versions.properties文件,增加如下配置

/com.yahoo.platform.yui/yuicompressor = 2.4.8

2、配置依赖yuicompressor包的配置

打开ivy.xml文件,增加依赖yuicompressor包的配置,以便于执行ant时自动下载该jar包。

<dependency org="com.yahoo.platform.yui" name="yuicompressor" rev="${/com.yahoo.platform.yui/yuicompressor}" conf="compressor"/>

3、配置js文件和ccs文件压缩的配置

打开build.xml文件,增加调用yuicompressor包对js文件和ccs文件压缩的配置。

  <property name="yuicompressor" value="${server.dir}/lib/yuicompressor-2.4.8.jar" />
  <property name="jsdirectory" value="${common-solr.dir}/webapp/web/js/angular" />
<property name="cssdirectory" value="${common-solr.dir}/webapp/web/css/angular" />

  <target name="compress-js-and-css">
    <!--compress js-->
    <apply executable="java" parallel="false" failonerror="true" dest="${jsdirectory}/" append="false" force="true">

        <!--compress several source directories-->
        <fileset dir="${jsdirectory}/" includes="*.js"/>
        <fileset dir="${jsdirectory}/" includes="controllers/*.js"/>

        <arg line="-jar" />
        <arg path="${yuicompressor}" />
        <arg line="--nomunge" />
        <arg line="--charset UTF-8" />
        <srcfile />
        <arg line="-o" />
        <mapper type="glob" from="*.js" to="*.js" />
        <targetfile />
    </apply>

    <!--compress css-->
    <apply executable="java" parallel="false" failonerror="true" dest="${cssdirectory}/" append="false" force="true">

        <!--compress several source directories-->
        <fileset dir="${cssdirectory}/" includes="*.css"/>

        <arg line="-jar" />
        <arg path="${yuicompressor}" />
        <arg line="--nomunge" />
        <arg line="--charset UTF-8" />
        <srcfile />
        <arg line="-o" />
        <mapper type="glob" from="*.css" to="*.css" />
        <targetfile />
    </apply>
  </target>

常见问题:

1、使用yuicompressor压缩js时报错的解决方案

$ java -jar /C/Users/wkh/Downloads/yuicompressor-2.4.8.jar -o '.js$:-min.js' *.js --charset utf-8 --nomunge
[ERROR] in analysis.js
  47:18:missing variable name
[ERROR] in analysis.js
  49:27:syntax error
[ERROR] in analysis.js
  50:21:identifier is a reserved word
[ERROR] in analysis.js
  104:26:invalid property id
[ERROR] in analysis.js
  104:27:syntax error
[ERROR] in analysis.js
  105:30:syntax error
[ERROR] in analysis.js
  106:28:syntax error
[ERROR] in analysis.js
  1:0:Compilation produced 7 syntax errors.
org.mozilla.javascript.EvaluatorException: Compilation produced 7 syntax errors.
        at com.yahoo.platform.yui.compressor.YUICompressor$1.runtimeError(YUICompressor.java:172)
        at org.mozilla.javascript.Parser.parse(Parser.java:396)
        at org.mozilla.javascript.Parser.parse(Parser.java:340)
        at com.yahoo.platform.yui.compressor.JavaScriptCompressor.parse(JavaScriptCompressor.java:315)
        at com.yahoo.platform.yui.compressor.JavaScriptCompressor.<init>(JavaScriptCompressor.java:536)
        at com.yahoo.platform.yui.compressor.YUICompressor.main(YUICompressor.java:147)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at com.yahoo.platform.yui.compressor.Bootstrap.main(Bootstrap.java:21)

报错主要是因为js源文件中有js关键字和保留字定义的变量或参数。因此可以将这些变量名进行变更,将参数用['parameter']的方式替换。
例如:
(1)变更变量名

        var short = -1 !== longname.indexOf( '$' )
                         ? longname.split( '$' )[1]
                         : longname.split( '.' ).pop();
        return short.match( /[A-Z]/g ).join( '' );

变量名short是js保留字,可以修改为shortComponentName。

        var shortComponentName = -1 !== longname.indexOf( '$' )
                         ? longname.split( '$' )[1]
                         : longname.split( '.' ).pop();
        return shortComponentName.match( /[A-Z]/g ).join( '' );

(2)变更参数获取方式

 logger.short = shortNameOf(logger);

将.short参数用['short']的方式替换

logger['short'] = shortNameOf(logger);

2、如何跳过许可/信用时的注释,使用YUIcompressor压缩JavaScript?

按照如下方式对许可/信用进行注释,感叹号告诉压缩器保留注释。

/*!
 *
 */

相关文章

  • ant+yuicompressor压缩js/css

    ant+yuicompressor在前端部署和服务器发布中用处极大。我在项目中用到的是ant+yuicompres...

  • 前端知识汇总(渲染篇)

    前端优化的手段 js css压缩合并 css在上,js在下(defer,async) 图片压缩、CSS-sprit...

  • 压缩

    压缩 html css js 压缩图片

  • Gulp 使用gulp压缩CSS

    我们除了可以使用 gulp 压缩 JS 文件,还可以压缩 CSS,压缩 CSS 代码可以降低 CSS 文件的大小,...

  • Gulp 使用gulp压缩CSS

    我们除了可以使用 gulp 压缩 JS 文件,还可以压缩 CSS,压缩 CSS 代码可以降低 CSS 文件的大小,...

  • netcore 网站优化

    css 文件引用放在head里面,js文件引用放在body底部,css js用压缩工具压缩成min.css 和mi...

  • vue-cli3 之vue.config.js配置

    1、 cdn、全局cdn(所有的js、css都使用cdn)2、Gzip压缩(压缩js、css)3、去掉注释、去掉c...

  • webpack 代码压缩

    js文件压缩 webpack 4 内置了uglifyjs-webpack-plugin,js默认是压缩过的 css...

  • webpack学习笔记(3)

    1、HTML、CSS和JS代码压缩 JS文件的压缩webpack4内置了uglifyjs-webpack-plug...

  • 前端工具

    在日常的前端开发中,我们会遇到 LESS/SASS 编译、CSS 前缀自动补全 、CSS 压缩、 图片压缩、JS ...

网友评论

      本文标题:ant+yuicompressor压缩js/css

      本文链接:https://www.haomeiwen.com/subject/xwxyictx.html