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

如何在AngularJS中实现类似Angular 5的环境变量(API URL)配置?

How to Implement Angular CLI-style Environment Variables in AngularJS

Great question! I totally get why you’re a fan of Angular CLI’s src/environments setup—it’s a clean, maintainable way to separate development and production configurations without cluttering your application code. Let’s break down a practical way to replicate this workflow in AngularJS.

Step 1: Create Environment Configuration Files

First, set up a dedicated environments folder in your project (just like Angular CLI) with separate files for each environment:

  • environments/environment.dev.js (development config)
  • environments/environment.prod.js (production config)

Here’s what these files might look like:

environment.dev.js

export const environment = {
  production: false,
  apiUrl: 'http://localhost:61006'
};

environment.prod.js

export const environment = {
  production: true,
  apiUrl: 'http://intel-api-interactivechoices.azurewebsites.net'
};

If your project doesn’t use ES6 modules, you can attach the config to the global window object instead:

// environment.dev.js
window.environment = {
  production: false,
  apiUrl: 'http://localhost:61006'
};

Step 2: Set Up Build-Time File Replacement

The key here is to swap the active environment file during your build process. Most AngularJS projects use Gulp or Webpack for builds—here’s how to handle both:

Option A: Using Gulp

Create a Gulp task that copies the correct environment file to a location your app can access (like src/app/environment.js) based on a build flag:

const gulp = require('gulp');
const rename = require('gulp-rename');
const argv = require('yargs').argv;

gulp.task('set-environment', () => {
  const env = argv.env || 'dev';
  return gulp.src(`environments/environment.${env}.js`)
    .pipe(rename('environment.js'))
    .pipe(gulp.dest('src/app/'));
});

// Add this task as a dependency to your main build task
gulp.task('build', gulp.series('set-environment', /* your existing build tasks */));

Run your build with the desired environment:

# Development build
gulp build --env=dev

# Production build
gulp build --env=prod

Option B: Using Webpack

Use Webpack’s DefinePlugin to inject environment variables directly, or use copy-webpack-plugin to copy the right file:

Using DefinePlugin (inline variables)

// webpack.config.js
const webpack = require('webpack');
const argv = require('yargs').argv;

const env = argv.env || 'dev';
const envConfig = require(`./environments/environment.${env}.js`);

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

Using copy-webpack-plugin (file replacement)

// webpack.config.js
const CopyPlugin = require('copy-webpack-plugin');
const argv = require('yargs').argv;

const env = argv.env || 'dev';

module.exports = {
  // ... other config
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: `environments/environment.${env}.js`,
          to: 'environment.js',
          context: './'
        }
      ]
    })
  ]
};

Run Webpack with the environment flag:

# Development build
webpack --env=dev

# Production build
webpack --env=prod

Step 3: Inject Environment Config into AngularJS

Now, make the environment config available in your AngularJS app. If you used ES6 modules, import it and register it as a constant:

// src/app/app.module.js
import { environment } from './environment';

angular.module('myApp', [])
  .constant('environment', environment);

If you used the global window object, register it like this:

angular.module('myApp', [])
  .constant('environment', window.environment);

Then use it in your controllers, services, etc.:

angular.module('myApp')
  .controller('MyController', ['environment', function(environment) {
    console.log('API URL:', environment.apiUrl);
    console.log('Production mode:', environment.production);
  }]);

Step 4: Add NPM Scripts (Optional)

To make builds even easier, add scripts to your package.json:

{
  "scripts": {
    "build:dev": "gulp build --env=dev", // or webpack --env=dev
    "build:prod": "gulp build --env=prod" // or webpack --env=prod
  }
}

Now you can run npm run build:dev or npm run build:prod to switch environments quickly.


This setup mirrors Angular CLI’s environment workflow perfectly—you keep environment-specific configs separate, avoid hardcoding values, and can switch between environments with a single build command.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:01:34