构建Angular应用时如何读取系统环境变量并替换配置值?
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.jsin 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.jsonto use the custom builder. Findprojects -> [your-project-name] -> architect -> buildand modify the builder and options:
If you use"builder": "@angular-builders/custom-webpack:browser", "options": { "customWebpackConfig": { "path": "./webpack.extra.js" }, // Keep all your existing build options (outputPath, index, main, etc.) }ng servefor development, you can also update theservearchitect to use@angular-builders/custom-webpack:dev-serverthe 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.jsonunderprojects -> [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.jsto load the.envfile: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
.envfile 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 viaDefinePlugin—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.,
--prodor--configuration=production) to ensure optimizations and proper environment file replacement. - System environment variables take precedence over
.envvalues, which is ideal for CI/CD where you can set vars directly in the pipeline without modifying files.
内容的提问来源于stack exchange,提问作者Abhishek Garg

