maven-replacer-plugin 靜態資源版本號解決方案(css/js等)


本文介紹如何使用 maven 的 com.google.code.maven-replacer-plugin 插件來自動添加版本號,防止瀏覽器緩存。


目錄

  • 1.解決方案
  • 2.原始文件和最終生成效果
  • 3.pom.xml 中插件添加
  • 4.html中 css/js 文件引用規則
  • 5.結語

1.解決方案

解決問題:
    防止瀏覽器緩存,修改靜態文件(js/css)后無效,需要強刷。

解決方案:
    使用 maven 的 com.google.code.maven-replacer-plugin 插件,
    在項目打包 package 時自動為靜態文件追加 xxx.js?v=time 的后綴,
    從而解決瀏覽器修改后瀏覽器緩存問題,此插件只會在生成 war 包源碼時生效,不需要修改任何代碼。

2.原始文件和最終生成效果

原始文件:
<script src="${resource!}/js/xxx/xxx.js"></script>

打包后:
<script src="${resource!}/js/xxx/xxx.js?v=20180316082543"></script>

3.pom.xml 中插件添加


<properties>
	<!-- maven.build.timestamp 默認時間戳格式 -->
	<maven.build.timestamp.format>yyyyMMddHHmmss</maven.build.timestamp.format>
</properties>

<plugins>
    <plugin>
		<groupId>org.apache.maven.plugins</groupId>
		<artifactId>maven-war-plugin</artifactId>
		<configuration>
			<!-- 使用緩存 -->
			<useCache>true</useCache>
		</configuration>
		<executions>
			<!-- 在打包之前執行,打包后包含已經執行后的文件 -->
			<execution>
				<id>prepare-war</id>
				<phase>prepare-package</phase>
				<goals>
					<goal>exploded</goal>
				</goals>
			</execution>
		</executions>
	</plugin>
	<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>
			<!-- 自動識別到項目target文件夾 -->
			<basedir>${build.directory}</basedir>
			<!-- 替換的文件所在目錄規則 -->
			<includes>
				<include>${build.finalName}/WEB-INF/views/*.html</include>
				<include>${build.finalName}/WEB-INF/views/**/*.html</include>
			</includes>
			<replacements>
				<!-- 更改規則,在css/js文件末尾追加?v=時間戳,反斜杠表示字符轉義 -->
				<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>
</plugins> 

4.html中 css/js 文件引用規則

文件引用結尾處,必須是pom.xml文件中添加的規則:

<script src="${resource!}/js/xxx/xxx.js" type="text/javascript"></script>

<link href="${resource!}/css/xxx/xxx.css" rel="stylesheet" type="text/css">

5.結語

到此本文就結束了,關注公眾號查看更多推送!!!


關注我的公眾號



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM