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

构建Angular应用时如何读取系统环境变量并替换配置值?

在Angular构建时通过系统环境变量替换Environment中的配置值

Hey there! Let's break this down into two parts: first, exactly how to replace your environment.ts's serveUrl with http://google.com using a system environment variable during ng build, then covering the general methods for reading system env vars in Angular builds.


Part 1: Specific Implementation - Replace serveUrl with http://google.com

1. Update Your Environment File

First, adjust your src/environments/environment.ts to accept an environment variable, with a fallback for development:

export const environment = {
  production: false,
  // Fallback to your local dev URL if no env var is set
  serveUrl: process.env.SERVE_URL || 'http://localhost:3000'
};

2. Configure Angular CLI to Parse Environment Variables

By default, Angular CLI doesn't handle process.env out of the box. We'll use @angular-builders/custom-webpack to extend the Webpack config and make this work:

  • Install the dependency first:
    npm install @angular-builders/custom-webpack --save-dev
    
  • Create a custom Webpack config file webpack.extra.js in your project root:
    const webpack = require('webpack');
    
    module.exports = {
      plugins: [
        new webpack.DefinePlugin({
          // Wrap the value in JSON.stringify to ensure it's treated as a string
          'process.env.SERVE_URL': JSON.stringify(process.env.SERVE_URL)
        })
      ]
    };
    
  • Update your angular.json to use the custom builder. Find projects -> [your-project-name] -> architect -> build and modify the builder and options:
    "builder": "@angular-builders/custom-webpack:browser",
    "options": {
      "customWebpackConfig": {
        "path": "./webpack.extra.js"
      },
      // Keep all your existing build options (outputPath, index, main, etc.)
    }
    
    If you use ng serve for development, you can also update the serve architect to use @angular-builders/custom-webpack:dev-server the same way.

3. Run the Build with the System Environment Variable

Now you can set the SERVE_URL env var and run the build command:

  • Linux/macOS Terminal:
    SERVE_URL=http://google.com ng build
    
  • Windows Command Prompt:
    set SERVE_URL=http://google.com && ng build
    
  • Windows PowerShell:
    $env:SERVE_URL="http://google.com"; ng build
    

After building, your app's environment.serveUrl will be set to http://google.com.


Part 2: General Methods for Reading System Environment Variables in Angular Builds

Here are a few common approaches depending on your use case:

Method 1: Angular Environment Configurations + Command Line Flags

If you have fixed environment-specific values (not dynamic system vars), you can create multiple environment files and switch between them with --configuration:

  • Create src/environments/environment.prod.google.ts:
    export const environment = {
      production: true,
      serveUrl: 'http://google.com'
    };
    
  • Add a new configuration to angular.json under projects -> [your-project] -> architect -> build -> configurations:
    "prod-google": {
      "fileReplacements": [
        {
          "replace": "src/environments/environment.ts",
          "with": "src/environments/environment.prod.google.ts"
        }
      ],
      // Copy over all your production config settings (optimization, outputHashing, etc.)
    }
    
  • Build with:
    ng build --configuration=prod-google
    

Method 2: Use .env Files with dotenv

If you prefer managing env vars in a .env file (great for local development), combine it with dotenv:

  • Install dotenv:
    npm install dotenv --save-dev
    
  • Update your webpack.extra.js to load the .env file:
    const webpack = require('webpack');
    // Load variables from .env file
    require('dotenv').config();
    
    module.exports = {
      plugins: [
        new webpack.DefinePlugin({
          'process.env.SERVE_URL': JSON.stringify(process.env.SERVE_URL)
        })
      ]
    };
    
  • Create a .env file in your project root:
    SERVE_URL=http://google.com
    

Run ng build and it'll pick up the value from .env. Plus, system environment variables will override .env values if set—perfect for CI/CD pipelines.

Method 3: Quick-and-Dirty File Replacement (No Dependencies)

If you don't want to add extra packages, you can use system text-replace commands to modify the environment file before building:

  • Linux/macOS:
    sed -i '' 's/serveUrl: .*/serveUrl: "http:\/\/google.com"/' src/environments/environment.ts && ng build
    
  • Windows PowerShell:
    (Get-Content src/environments/environment.ts) -replace 'serveUrl: .*', 'serveUrl: "http://google.com"' | Set-Content src/environments/environment.ts; ng build
    

This is a quick fix but less flexible for dynamic values or multiple variables.


Pro Tips

  • Always use JSON.stringify() when passing values via DefinePlugin—otherwise, Webpack will treat the value as code instead of a string.
  • For production builds, make sure you're using the correct configuration (e.g., --prod or --configuration=production) to ensure optimizations and proper environment file replacement.
  • System environment variables take precedence over .env values, which is ideal for CI/CD where you can set vars directly in the pipeline without modifying files.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:47:12