如何在React项目的index.html中引用package.json版本号并构建生效?
根据你的需求,以下是几种不同React项目脚手架下的可行方案:
1. Create React App(CRA)项目
CRA支持通过自定义环境变量传递版本号,步骤如下:
步骤1:修改package.json的build命令
为了跨平台兼容,先安装cross-env(如果还没装):npm install cross-env --save-dev然后在
package.json的scripts里更新build命令:"scripts": { "build": "cross-env REACT_APP_VERSION=$npm_package_version react-scripts build" }(如果是Windows纯CMD环境,也可以不用cross-env,直接写
"build": "set REACT_APP_VERSION=%npm_package_version% && react-scripts build")步骤2:在index.html中引用变量
打开public/index.html,把script标签修改为:<html> <body> ... <script src="index.hash.js?v=%REACT_APP_VERSION%"></script> </body> </html>执行
npm run build后,最终生成的HTML里会自动替换成package.json中的版本号。
2. Vite React项目
Vite自带环境变量处理能力,两种方式可选:
方式一:直接使用npm环境变量
Vite会自动暴露npm相关的环境变量,直接在index.html中引用:
<html> <body> ... <script src="/index.hash.js?v=%npm_package_version%"></script> </body> </html>
执行npm run build即可自动替换版本号,无需额外配置。
方式二:通过Vite配置自定义变量
如果需要更灵活的控制,在vite.config.js中添加配置:
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; import pkg from './package.json'; export default defineConfig({ plugins: [react()], define: { 'import.meta.env.APP_VERSION': JSON.stringify(pkg.version) } });
然后在index.html中引用:
<script src="/index.hash.js?v=%import.meta.env.APP_VERSION%"></script>
3. 自定义Webpack配置的React项目
如果你的项目用了自定义Webpack配置,借助html-webpack-plugin实现:
步骤1:确保已安装html-webpack-plugin
npm install html-webpack-plugin --save-dev步骤2:修改Webpack配置文件
const HtmlWebpackPlugin = require('html-webpack-plugin'); const pkg = require('./package.json'); module.exports = { // ...其他Webpack配置 plugins: [ new HtmlWebpackPlugin({ template: './public/index.html', inject: 'body', version: pkg.version // 传递版本号到模板 }) ] };步骤3:在index.html中使用变量
<html> <body> ... <script src="index.hash.js?v=<%= htmlWebpackPlugin.options.version %>"></script> </body> </html>
注意事项
HTML中的<script>标签不建议使用自闭合写法(<script />),标准写法应为<script></script>,避免部分浏览器解析异常。
内容的提问来源于stack exchange,提问作者Humberto Jr

