You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 17+构建时如何将package.json版本注入index.html的head中?

在Angular 17+构建时将package.json版本注入HTML的标签

方法一:用脚本批量替换占位符

这种方式简单直接,无需修改Angular构建核心配置:

  1. 安装替换工具:
npm install replace-in-file --save-dev
  1. 在src/index.html的<head>中添加版本占位符:
<meta name="version" content="VERSION_PLACEHOLDER" />
  1. 修改package.json的构建脚本,添加版本替换步骤:
"scripts": {
  "build": "ng build && npm run replace-version",
  "replace-version": "replace-in-file --config replace-version.config.js"
}
  1. 在项目根目录创建replace-version.config.js配置文件:
const packageJson = require('./package.json');

module.exports = {
  files: './dist/[你的项目名称]/index.html', // 替换为实际的dist输出路径
  from: /VERSION_PLACEHOLDER/g,
  to: packageJson.version,
};

执行npm run build后,dist目录下的index.html中占位符会被替换为package.json里的版本号。

方法二:通过自定义Webpack配置注入(推荐)

利用Angular的自定义Webpack扩展,直接通过html-webpack-plugin注入meta标签:

  1. 安装自定义Webpack构建器:
npm install @angular-builders/custom-webpack --save-dev
  1. 修改angular.json中的构建配置,替换默认builder:
"architect": {
  "build": {
    "builder": "@angular-builders/custom-webpack:browser",
    "options": {
      "customWebpackConfig": {
        "path": "./custom-webpack.config.js"
      },
      // 保留原有其他配置(如outputPath、index、main等)
    }
  }
}
  1. 在项目根目录创建custom-webpack.config.js:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const packageJson = require('./package.json');

module.exports = {
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
      meta: {
        version: packageJson.version
      }
    })
  ]
};

执行构建后,HTML的<head>中会自动生成meta标签,无需手动添加占位符。

内容的提问来源于stack exchange,提问作者hairbo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 20:55:02