maven 绑定html压缩,使用Maven 压缩、合并前端静态资源

先来看看工程结构:

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 时方便筛选。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值