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

Angular 16构建时如何通过CLI动态传递API地址参数?

实现Angular 16构建时动态传递API地址

方案1:通过Webpack注入环境变量(推荐)

步骤1:修改环境文件

将src/environments/environment.ts中的API地址改为读取环境变量:

export const environment = {
    apiUrl: process.env.SERVER_URL || 'http://default.server.url:port/'
};

步骤2:配置自定义Webpack

首先安装依赖:

npm install @angular-builders/custom-webpack --save-dev

修改angular.json的build配置,替换默认builder并指定自定义Webpack配置文件:

"architect": {
  "build": {
    "builder": "@angular-builders/custom-webpack:browser",
    "options": {
      "customWebpackConfig": {
        "path": "./webpack.config.js"
      },
      // 保留原有其他配置
    },
    "configurations": {
      "production": {
        "fileReplacements": [
          {
            "replace": "src/environments/environment.development.ts",
            "with": "src/environments/environment.ts"
          }
        ],
        // 保留原有其他production配置
      }
    }
  }
}

在项目根目录创建webpack.config.js,用DefinePlugin注入环境变量:

const webpack = require('webpack');

module.exports = {
  plugins: [
    new webpack.DefinePlugin({
      'process.env.SERVER_URL': JSON.stringify(process.env.SERVER_URL)
    })
  ]
};

步骤3:动态构建

执行构建命令时直接传递环境变量:

# Linux/Mac
SERVER_URL=http://55.66.77.88:5678/ ng build --configuration=production

# Windows CMD
set SERVER_URL=http://55.66.77.88:5678/ && ng build --configuration=production

方案2:构建后文本替换(无需额外依赖)

步骤1:修改环境文件占位符

将src/environments/environment.ts中的API地址改为唯一占位符:

export const environment = {
    apiUrl: '__SERVER_URL_PLACEHOLDER__'
};

步骤2:添加npm脚本

在package.json中新增构建脚本,完成构建后替换占位符:

"scripts": {
  "build:prod": "ng build --configuration=production && sed -i 's/__SERVER_URL_PLACEHOLDER__/'"$SERVER_URL"'/g' dist/你的项目名/main*.js"
}

步骤3:动态构建

执行脚本时传递目标地址:

SERVER_URL=http://55.66.77.88:5678/ npm run build:prod

注:Windows系统需将sed替换为PowerShell的-replace命令,示例:

$env:SERVER_URL="http://55.66.77.88:5678/"; ng build --configuration=production; (Get-Content dist/你的项目名/main*.js) -replace '__SERVER_URL_PLACEHOLDER__', $env:SERVER_URL | Set-Content dist/你的项目名/main*.js

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 01:52:49