通过maven-replacer-plugin插件可以为打包的前端文件中所引用的JS、CSS文件添加版本号,从而在每次代码重新部署后可及时更新用户缓存。
配置过程如下:
配置日期输出格式,默认日期按照
yyyy-MM-ddTHH:mm:ss
格式输出,作为版本戳较为不美观<properties> <maven.build.timestamp.format>yyyyMMddHHmmss</maven.build.timestamp.format> </properties>
配置maven-war-plugin
- phase选择与下方maven-replacer-plugin相同的prepare-package阶段,即此部分为打包前执行
- goal选择exploded,即不生成war包,仅获得解压后的文件内容
- configuration中设置useCache为true,即使用已解压文件进行打包
- version设置为2.4,实测2.1.1和2.2版本均会报
Cannot construct org.apache.maven.plugin.war.util.WebappStructure as it does not have a no-args constructor
错误
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <!-- 使用缓存 --> <useCache>true</useCache> </configuration> <executions> <!-- 在打包之前执行,打包后包含已经执行后的文件 --> <execution> <id>prepare-war</id> <phase>prepare-package</phase> <goals> <goal>exploded</goal> </goals> </execution> </executions> </plugin>
配置maven-replacer-plugin插件
- basedir配置所要替换文件的所在目录,${build.directory}即为项目的target目录
- includes中可设置要查找的文件类型,
**/*.html
即表示所有目录及子目录下的.html后缀文件 - 默认状态下替换的token使用正则表达式进行匹配,会将匹配到的内容替换为value中设置的内容
<plugin> <groupId>com.google.code.maven-replacer-plugin</groupId> <artifactId>replacer</artifactId> <version>1.5.3</version> <executions> <execution> <phase>prepare-package</phase> <goals> <goal>replace</goal> </goals> </execution> </executions> <configuration> <basedir>${build.directory}</basedir> <includes> <include>**/*.html</include> </includes> <replacements> <replacement> <token>\.css\"</token> <value>.css?v=${maven.build.timestamp}\"</value> </replacement> <replacement> <token>\.css\'</token> <value>.css?v=${maven.build.timestamp}\'</value> </replacement> <replacement> <token>\.js\"</token> <value>.js?v=${maven.build.timestamp}\"</value> </replacement> <replacement> <token>\.js\'</token> <value>.js?v=${maven.build.timestamp}\'</value> </replacement> </replacements> </configuration> </plugin>
常见问题
- Replacement run on 0 files.未找到需替换文件,路径有误,或phase设置错误
- 文件内容未替换,useCache未设置,在package阶段再次执行maven-war-plugin时新文件将已替换内容的文件覆盖了
Cannot construct org.apache.maven.plugin.war.util.WebappStructure as it does not have a no-args constructor
错误,版本设置有误
参考资料:
1记录com.google.code.maven-replacer-plugin找不到文件
2Cannot construct org.apache.maven.plugin.war.util.WebappStructure as it does not have a no-args constructor