如何管理不同环境的配置变量/常数?

这可以是一个例子:

我的其余API可以在localhost:7080/myapi/上访问,但是我的朋友在Git版本控制下使用相同的代码,他在localhost:8099/hisapi/上的Tomcat上部署了API。

假设我们有这样的东西:

angular
    .module('app', ['ngResource'])

    .constant('API_END_POINT','<local_end_point>')

    .factory('User', function($resource, API_END_POINT) {
        return $resource(API_END_POINT + 'user');
    });

我如何动态地注入API端点的正确值,取决于环境?

在PHP中,我通常使用config.username.xml文件来完成这类工作,将基本配置文件(config.xml)与由用户名识别的本地环境配置文件合并。但我不知道如何在JavaScript中管理这种事情?


好问题!

一种解决方案是继续使用config.xml文件,并从后端向生成的html提供api端点信息,如下所示(以php为例):

<script type="text/javascript">
angular.module('YourApp').constant('API_END_POINT', '<?php echo $apiEndPointFromBackend; ?>');
</script>

也许不是一个漂亮的解决方案,但它会起作用。

另一种解决方案可能是保持API_END_POINT常量值,因为它应该在生产环境中,并且只修改您的hosts-file来将url指向您的本地api。

或者使用localStorage来重写,就像这样:

.factory('User',['$resource','API_END_POINT'],function($resource,API_END_POINT){
   var myApi = localStorage.get('myLocalApiOverride');
   return $resource((myApi || API_END_POINT) + 'user');
});

一个很酷的解决方案可能是将所有特定于环境的值分离到某个单独的角模块中,所有其他模块都依赖于它:

angular.module('configuration', [])
       .constant('API_END_POINT','123456')
       .constant('HOST','localhost');

然后需要这些条目的模块可以声明对它的依赖:

angular.module('services',['configuration'])
       .factory('User',['$resource','API_END_POINT'],function($resource,API_END_POINT){
           return $resource(API_END_POINT + 'user');
       });

现在你可以想想更酷的东西:

包含配置的模块可以被分离到configuration.js中,它将包含在你的页面中。

只要不将这个单独的文件签入git,每个人都可以轻松地编辑这个脚本。但是,如果配置在一个单独的文件中,则更容易不签入配置。此外,您还可以在本地对其进行分支。

现在,如果您有一个构建系统,如ANT或Maven,您的进一步步骤可能是为API_END_POINT值实现一些占位符,这些占位符将在构建时用您的特定值替换。

或者你有你的configuration_a.js和configuration_b.js,并在后端决定包含哪个。


你看过这个问题和答案吗?

你可以像这样为你的应用程序设置一个全局有效值:

app.value('key', 'value');

然后用在你的服务上。您可以将这段代码移动到config.js文件中,并在页面加载或其他方便的时候执行。


你可以用lvh。me:9000来访问你的AngularJS应用程序,(lvh。Me只是指向127.0.0.1),然后指定一个不同的端点如果lvh。我是主持人:

app.service("Configuration", function() {
  if (window.location.host.match(/lvh\.me/)) {
    return this.API = 'http://localhost\\:7080/myapi/';
  } else {
    return this.API = 'http://localhost\\:8099/hisapi/';
  }
});

然后注入Configuration服务并使用Configuration。当你需要访问API时:

$resource(Configuration.API + '/endpoint/:id', {
  id: '@id'
});

有点笨拙,但对我来说很好,尽管在稍微不同的情况下(API端点在生产和开发中不同)。


我有点晚了,但如果你正在使用Grunt,我已经成功地使用了Grunt -ng-constant。

在我的Gruntfile.js中ngconstant的配置部分看起来像这样

ngconstant: {
  options: {
    name: 'config',
    wrap: '"use strict";\n\n{%= __ngModule %}',
    space: '  '
  },
  development: {
    options: {
      dest: '<%= yeoman.app %>/scripts/config.js'
    },
    constants: {
      ENV: 'development'
    }
  },
  production: {
    options: {
      dest: '<%= yeoman.dist %>/scripts/config.js'
    },
    constants: {
      ENV: 'production'
    }
  }
}

使用ngconstant的任务如下所示

grunt.registerTask('server', function (target) {
  if (target === 'dist') {
    return grunt.task.run([
      'build',
      'open',
      'connect:dist:keepalive'
    ]);
  }

  grunt.task.run([
    'clean:server',
    'ngconstant:development',
    'concurrent:server',
    'connect:livereload',
    'open',
    'watch'
  ]);
});

grunt.registerTask('build', [
  'clean:dist',
  'ngconstant:production',
  'useminPrepare',
  'concurrent:dist',
  'concat',
  'copy',
  'cdnify',
  'ngmin',
  'cssmin',
  'uglify',
  'rev',
  'usemin'
]);

因此,运行grunt服务器将在app/scripts/中生成一个config.js文件,看起来像

"use strict";
angular.module("config", []).constant("ENV", "development");

最后,我声明依赖于任何需要它的模块:

// the 'config' dependency is generated via grunt
var app = angular.module('myApp', [ 'config' ]);

现在我的常量可以在需要的地方被注入依赖项。例如,

app.controller('MyController', ['ENV', function( ENV ) {
  if( ENV === 'production' ) {
    ...
  }
}]);

如果你使用Brunch, Constangular插件可以帮助你管理不同环境的变量。


对于Gulp用户,Gulp -ng-constant与Gulp -concat、event-stream和yargs结合使用也很有用。

var concat = require('gulp-concat'),
    es = require('event-stream'),
    gulp = require('gulp'),
    ngConstant = require('gulp-ng-constant'),
    argv = require('yargs').argv;

var enviroment = argv.env || 'development';

gulp.task('config', function () {
  var config = gulp.src('config/' + enviroment + '.json')
    .pipe(ngConstant({name: 'app.config'}));
  var scripts = gulp.src('js/*');
  return es.merge(config, scripts)
    .pipe(concat('app.js'))
    .pipe(gulp.dest('app/dist'))
    .on('error', function() { });
});

在我的配置文件夹中有这些文件:

ls -l config
total 8
-rw-r--r--+ 1 .. ci.json
-rw-r--r--+ 1 .. development.json
-rw-r--r--+ 1 .. production.json

然后你可以运行gulp config—env development,它将创建如下内容:

angular.module("app.config", [])
.constant("foo", "bar")
.constant("ngConstant", true);

我还有这个说明:

beforeEach(module('app'));

it('loads the config', inject(function(config) {
  expect(config).toBeTruthy();
}));

为了达到这个目的,我建议你使用AngularJS环境插件:https://www.npmjs.com/package/angular-environment

这里有一个例子:

angular.module('yourApp', ['environment']).
config(function(envServiceProvider) {
    // set the domains and variables for each environment 
    envServiceProvider.config({
        domains: {
            development: ['localhost', 'dev.local'],
            production: ['acme.com', 'acme.net', 'acme.org']
            // anotherStage: ['domain1', 'domain2'], 
            // anotherStage: ['domain1', 'domain2'] 
        },
        vars: {
            development: {
                apiUrl: '//localhost/api',
                staticUrl: '//localhost/static'
                // antoherCustomVar: 'lorem', 
                // antoherCustomVar: 'ipsum' 
            },
            production: {
                apiUrl: '//api.acme.com/v2',
                staticUrl: '//static.acme.com'
                // antoherCustomVar: 'lorem', 
                // antoherCustomVar: 'ipsum' 
            }
            // anotherStage: { 
            //  customVar: 'lorem', 
            //  customVar: 'ipsum' 
            // } 
        }
    });

    // run the environment check, so the comprobation is made 
    // before controllers and services are built 
    envServiceProvider.check();
});

然后,你可以从你的控制器调用变量,像这样:

envService.read('apiUrl');

希望能有所帮助。


我们也可以这样做。

(function(){
    'use strict';

    angular.module('app').service('env', function env() {

        var _environments = {
            local: {
                host: 'localhost:3000',
                config: {
                    apiroot: 'http://localhost:3000'
                }
            },
            dev: {
                host: 'dev.com',
                config: {
                    apiroot: 'http://localhost:3000'
                }
            },
            test: {
                host: 'test.com',
                config: {
                    apiroot: 'http://localhost:3000'
                }
            },
            stage: {
                host: 'stage.com',
                config: {
                apiroot: 'staging'
                }
            },
            prod: {
                host: 'production.com',
                config: {
                    apiroot: 'production'
                }
            }
        },
        _environment;

        return {
            getEnvironment: function(){
                var host = window.location.host;
                if(_environment){
                    return _environment;
                }

                for(var environment in _environments){
                    if(typeof _environments[environment].host && _environments[environment].host == host){
                        _environment = environment;
                        return _environment;
                    }
                }

                return null;
            },
            get: function(property){
                return _environments[this.getEnvironment()].config[property];
            }
        }

    });

})();

在你的控制器/服务中,我们可以注入依赖项并调用get方法来访问属性。

(function() {
    'use strict';

    angular.module('app').service('apiService', apiService);

    apiService.$inject = ['configurations', '$q', '$http', 'env'];

    function apiService(config, $q, $http, env) {

        var service = {};
        /* **********APIs **************** */
        service.get = function() {
            return $http.get(env.get('apiroot') + '/api/yourservice');
        };

        return service;
    }

})();

$http.get(env.get('apiroot')将根据主机环境返回url。


很晚才开始,但在使用angular之前,我使用了一种技术,就是利用JSON和JS的灵活性来动态引用集合键,并使用环境中不可分割的事实(主机服务器名、当前浏览器语言等)作为输入,在JSON数据结构中选择性地区分/偏爱带有后缀的键名。

这不仅提供了部署环境上下文(每个OP),还提供了任何任意上下文(例如语言),以同时提供i18n或任何其他所需的方差,并且(理想情况下)在单个配置清单中,没有重复,并且易于阅读。

在大约10行香草js

过度简化但经典的例子:json格式的属性文件中的API端点基URL,随着环境的不同(当然)主机服务器也会不同:

    ...
    'svcs': {
        'VER': '2.3',
        'API@localhost': 'http://localhost:9090/',
        'API@www.uat.productionwebsite.com': 'https://www.uat.productionwebsite.com:9090/res/',
        'API@www.productionwebsite.com': 'https://www.productionwebsite.com:9090/api/res/'
    },
    ...

识别函数的关键是请求中的服务器主机名。

当然,这可以与基于用户语言设置的附加键结合使用:

    ...
    'app': {
        'NAME': 'Ferry Reservations',
        'NAME@fr': 'Réservations de ferry',
        'NAME@de': 'Fähren Reservierungen'
    },
    ...

区分/偏好的范围可以限制在单个键(如上所述),其中“base”键只在函数输入有匹配的键+后缀时才会被覆盖——或者整个结构,并且该结构本身递归地解析匹配的区分/偏好后缀:

    'help': {
        'BLURB': 'This pre-production environment is not supported. Contact Development Team with questions.',
        'PHONE': '808-867-5309',
        'EMAIL': 'coder.jen@lostnumber.com'
    },
    'help@www.productionwebsite.com': {
        'BLURB': 'Please contact Customer Service Center',
        'BLURB@fr': 'S\'il vous plaît communiquer avec notre Centre de service à la clientèle',
        'BLURB@de': 'Bitte kontaktieren Sie unseren Kundendienst!!1!',
        'PHONE': '1-800-CUS-TOMR',
        'EMAIL': 'customer.service@productionwebsite.com'
    },

因此,如果产品网站的访问用户有德语(de)语言偏好设置,上述配置将崩溃为:

    'help': {
        'BLURB': 'Bitte kontaktieren Sie unseren Kundendienst!!1!',
        'PHONE': '1-800-CUS-TOMR',
        'EMAIL': 'customer.service@productionwebsite.com'
    },

这样一个神奇的偏好/歧视json重写函数是什么样的呢?没有多少:

// prefer(object,suffix|[suffixes]) by/par/durch storsoc
// prefer({ a: 'apple', a@env: 'banana', b: 'carrot' },'env') -> { a: 'banana', b: 'carrot' }
function prefer(o,sufs) {
    for (var key in o) {
        if (!o.hasOwnProperty(key)) continue; // skip non-instance props
        if(key.split('@')[1]) { // suffixed!
            // replace root prop with the suffixed prop if among prefs
            if(o[key] && sufs.indexOf(key.split('@')[1]) > -1) o[key.split('@')[0]] = JSON.parse(JSON.stringify(o[key]));

            // and nuke the suffixed prop to tidy up
            delete o[key];

            // continue with root key ...
            key = key.split('@')[0];
        }

        // ... in case it's a collection itself, recurse it!
        if(o[key] && typeof o[key] === 'object') prefer(o[key],sufs);

    };
};

在我们的实现中,包括Angular和pre-Angular的网站,我们简单地在其他资源调用之前引导配置,将JSON放置在一个自执行的JS闭包中,包括prefer()函数,并提供主机名和语言代码的基本属性(并接受你可能需要的任何额外的任意后缀):

(function(prefs){ var props = {
    'svcs': {
        'VER': '2.3',
        'API@localhost': 'http://localhost:9090/',
        'API@www.uat.productionwebsite.com': 'https://www.uat.productionwebsite.com:9090/res/',
        'API@www.productionwebsite.com': 'https://www.productionwebsite.com:9090/api/res/'
    },
    ...
    /* yadda yadda moar JSON und bisque */

    function prefer(o,sufs) {
        // body of prefer function, broken for e.g.
    };

    // convert string and comma-separated-string to array .. and process it
    prefs = [].concat( ( prefs.split ? prefs.split(',') : prefs ) || []);
    prefer(props,prefs);
    window.app_props = JSON.parse(JSON.stringify(props));
})([location.hostname, ((window.navigator.userLanguage || window.navigator.language).split('-')[0])  ] );

angular之前的站点现在会有一个折叠的(没有@后缀键)窗口。要引用的App_props。

Angular站点,作为bootstrap/init步骤,只是简单地将死挂的props对象复制到$rootScope中,并(可选地)从global/window作用域销毁它

app.constant('props',angular.copy(window.app_props || {})).run( function ($rootScope,props) { $rootScope.props = props; delete window.app_props;} );

随后注入控制器:

app.controller('CtrlApp',function($log,props){ ... } );

或者从视图中的绑定引用:

<span>{{ props.help.blurb }} {{ props.help.email }}</span>

警告?@字符不是有效的JS/JSON变量/键命名,但目前为止接受。如果这是一个交易破坏者,替换任何你喜欢的惯例,如“__”(双下划线),只要你坚持它。

该技术可以应用于服务器端,移植到Java或c#,但您的效率/紧凑性可能会有所不同。

或者,函数/约定可以是前端编译脚本的一部分,这样就不会通过网络传输完整的全环境/全语言JSON。

更新

我们已经改进了这种技术的用法,以允许对一个键使用多个后缀,以避免被迫使用集合(您仍然可以,只要您想要的深度),以及尊重首选后缀的顺序。

示例(也参见工作jsFiddle):

var o = { 'a':'apple', 'a@dev':'apple-dev', 'a@fr':'pomme',
          'b':'banana', 'b@fr':'banane', 'b@dev&fr':'banane-dev',
          'c':{ 'o':'c-dot-oh', 'o@fr':'c-point-oh' }, 'c@dev': { 'o':'c-dot-oh-dev', 'o@fr':'c-point-oh-dev' } };

/*1*/ prefer(o,'dev');        // { a:'apple-dev', b:'banana',     c:{o:'c-dot-oh-dev'}   }
/*2*/ prefer(o,'fr');         // { a:'pomme',     b:'banane',     c:{o:'c-point-oh'}     }
/*3*/ prefer(o,'dev,fr');     // { a:'apple-dev', b:'banane-dev', c:{o:'c-point-oh-dev'} }
/*4*/ prefer(o,['fr','dev']); // { a:'pomme',     b:'banane-dev', c:{o:'c-point-oh-dev'} }
/*5*/ prefer(o);              // { a:'apple',     b:'banana',     c:{o:'c-dot-oh'}       }

1/2(基本用法)倾向于“@dev”键,丢弃所有其他带有后缀的键

3 .“@dev”优于“@fr”,“@dev&fr”优于其他

4(与3相同,但更倾向于“@fr”而不是“@dev”)

5 .没有首选后缀,删除所有后缀属性

它通过对每个带有后缀的属性进行评分,并在遍历属性并找到得分更高的后缀时,将带有后缀的属性的值提升到未带有后缀的属性。

这个版本的一些效率,包括消除对JSON的深度复制依赖,只递归到在深度上存活的对象:

function prefer(obj,suf) {
    function pr(o,s) {
        for (var p in o) {
            if (!o.hasOwnProperty(p) || !p.split('@')[1] || p.split('@@')[1] ) continue; // ignore: proto-prop OR not-suffixed OR temp prop score
            var b = p.split('@')[0]; // base prop name
            if(!!!o['@@'+b]) o['@@'+b] = 0; // +score placeholder
            var ps = p.split('@')[1].split('&'); // array of property suffixes
            var sc = 0; var v = 0; // reset (running)score and value
            while(ps.length) {
                // suffix value: index(of found suffix in prefs)^10
                v = Math.floor(Math.pow(10,s.indexOf(ps.pop())));
                if(!v) { sc = 0; break; } // found suf NOT in prefs, zero score (delete later)
                sc += v;
            }
            if(sc > o['@@'+b]) { o['@@'+b] = sc; o[b] = o[p]; } // hi-score! promote to base prop
            delete o[p];
        }
        for (var p in o) if(p.split('@@')[1]) delete o[p]; // remove scores
        for (var p in o) if(typeof o[p] === 'object') pr(o[p],s); // recurse surviving objs
    }
    if( typeof obj !== 'object' ) return; // validate
    suf = ( (suf || suf === 0 ) && ( suf.length || suf === parseFloat(suf) ) ? suf.toString().split(',') : []); // array|string|number|comma-separated-string -> array-of-strings
    pr(obj,suf.reverse());
}