先来看看工程结构:
project
└─main
├─Java
└─webapp
├─app
│ │ index.html
│ │
│ ├─css
│ │ style.css
│ │
│ └─js
│ app1.js
│ app2.js
│ jQuery-1.9.1.min.js
│
└─WEB-INF
web.xml
index.html 里引用 app1.js 和 app2.js, 首先通过 yuicompressor-maven-plugin 对 app1.js,app2.js 进行压缩、合并。
pom.xml 配置如下,其中所有已经是 min 化的文件会被排除比如:jquery-1.9.1.min.js
net.alchim31.maven
yuicompressor-maven-plugin
1.3.0
compress
UTF-8
false
true
-1
app/js/*.js
app/js/*.css
**/**min.js
true
true
${project.build.directory}/${project.build.finalName}
${project.build.directory}/${project.build.finalName}/app/js/app.pack.js
app/js/app*.js
**/**min.js
这里我将 app1.js 和 app2.js 合并成 app.pack.js, 但光合并还不行。index.html 里仍然是引用 app1.js 和 app2.js,所以必须替换掉。
下一步用 maven-replacer-plugin 来完成替换工作。
为了通用性(你不必写死 js或者css文件名,并且支持多组的文件合并和替换),采用一个特殊的标识在 html 里来圈定要替换的js,这样就可以通过这个标识来寻找替换目标。
index.html
如上所示,所有 ... 区间的 js 引用会被替换成 xxx.js
增加的 maven-replacer-plugin pom 配置如下:
com.google.code.maven-replacer-plugin
replacer
1.5.2
package
replace
${project.build.directory}/${project.build.finalName}/app/index.html
(.*?)
]]>
]]>
CASE_INSENSITIVE
DOTALL
maven-replacer-plugin 支持正则替换正好满足我的需求,注意:
(1) 替换 区间的时候,使用的是正则 "单行” 模式,即 DOTALL
(2) 因为 yuicompressor-maven-plugin 执行在 prepackage 所以 maven-replacer-plugin 的 phase 要修改为 package
这样在开发时,增加 js 也不用再重复修改 pom 配置,当然 js 文件命名时最好遵从一定的规则,以便在 compress 时方便筛选。