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

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

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


目錄

  • 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文件中添加的規則:css

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

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

5.結語

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


關注個人公衆號
相關文章
相關標籤/搜索