如何将package.json版本与POM版本关联实现自动同步?
针对你用Maven Release插件更新版本后还要手动改package.json的痛点,我推荐两个能让版本自动同步的方案,完全不用额外加命令,用你原来的release:update-versions就能搞定:
方案1:用maven-replacer-plugin(无npm依赖)
这个方案靠正则替换直接修改package.json的版本字段,不需要依赖前端环境,适合纯Java+少量前端的项目。
- 在父POM的
<build><plugins>里添加replacer插件配置:
<plugin> <groupId>com.google.code.maven-replacer-plugin</groupId> <artifactId>replacer</artifactId> <version>1.5.3</version> <executions> <execution> <id>sync-package-json-version</id> <goals> <goal>replace</goal> </goals> <configuration> <file>package.json</file> <!-- 正则匹配带/不带SNAPSHOT的版本号,确保替换精准 --> <replacements> <replacement> <token>"version": "\d+\.\d+\.\d+(?:-SNAPSHOT)?"</token> <value>"version": "${project.version}"</value> </replacement> </replacements> <regex>true</regex> <!-- 多模块项目必须开这个,不然只会更新父模块的package.json --> <includeAllReactors>true</includeAllReactors> </configuration> </execution> </executions> </plugin>
- 给maven-release-plugin加个配置,让它更新完POM版本后自动触发替换:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-release-plugin</artifactId> <version>3.0.0</version> <configuration> <postUpdateVersionsGoals>replacer:replace</postUpdateVersionsGoals> </configuration> </plugin>
配置完之后,你执行原来的命令:
mvn --batch-mode release:update-versions -DdevelopmentVersion=X.X.X-SNAPSHOT
Maven会先把所有POM的版本更改为X.X.X-SNAPSHOT,然后自动遍历所有模块的package.json,把版本字段同步过去。
方案2:用frontend-maven-plugin(依赖npm,更严谨)
这个方案用npm官方的npm version命令更新版本,会自动同步package-lock.json的版本,避免正则可能出现的匹配错误,适合前端依赖较多的项目。
- 在父POM里添加frontend-maven-plugin配置:
<plugin> <groupId>com.github.eirslett</groupId> <artifactId>frontend-maven-plugin</artifactId> <version>1.12.1</version> <executions> <execution> <id>update-npm-version</id> <goals> <goal>npm</goal> </goals> <configuration> <!-- 用npm version更新版本,--no-git-tag-version避免自动打git标签 --> <arguments>version ${project.version} --no-git-tag-version</arguments> <includeAllReactors>true</includeAllReactors> </configuration> </execution> </executions> <!-- 可选:自动下载指定版本的node/npm,避免不同环境的版本差异 --> <configuration> <nodeVersion>v18.17.0</nodeVersion> <npmVersion>9.6.7</npmVersion> </configuration> </plugin>
- 同样给maven-release-plugin配置后置目标:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-release-plugin</artifactId> <version>3.0.0</version> <configuration> <postUpdateVersionsGoals>frontend:npm</postUpdateVersionsGoals> </configuration> </plugin>
执行原来的命令后,Maven会先更新POM版本,然后自动调用npm更新package.json和package-lock.json的版本,比正则替换更可靠。
几个注意点
- 多模块项目一定要开
<includeAllReactors>true</includeAllReactors>,不然只有父模块的package.json会被更新。 - 测试的时候可以加
-DdryRun=true参数,先预览版本更新效果,确认没问题再正式执行:mvn --batch-mode release:update-versions -DdevelopmentVersion=X.X.X-SNAPSHOT -DdryRun=true - 方案2中,frontend-maven-plugin会把node/npm下载到项目目录的
.frontend文件夹,不会影响全局环境,CI/CD环境也能正常使用。
内容的提问来源于stack exchange,提问作者Slayner
相关产品推荐
相关产品推荐

