问题描述
您如何管理不同环境的配置变量/常量?
How do you manage configuration variables/constants for different environments?
这可能是一个例子:
我的 rest API 可以在 localhost:7080/myapi/
上访问,但是我的朋友在 Git 版本控制下处理相同的代码,将 API 部署在 localhost:8099 上的 Tomcat 上/hisapi/
.
My rest API is reachable on localhost:7080/myapi/
, but my friend that works on the same code under Git version control has the API deployed on his Tomcat on localhost:8099/hisapi/
.
假设我们有这样的东西:
Supposing that we have something like this :
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 端点的正确值?
How do I dynamically inject the correct value of the API endpoint, depending on the environment?
在 PHP 中,我通常使用 config.username.xml
文件来做这种事情,将基本配置文件 (config.xml) 与通过名称识别的本地环境配置文件合并用户.但是我不知道如何在 JavaScript 中管理这种东西?
In PHP I usually do this kind of stuff with a config.username.xml
file, merging the basic configuration file (config.xml) with the local environment configuration file recognised by the name of the user. But I don't know how to manage this kind of thing in JavaScript?
推荐答案
我有点晚了,但如果你正在使用 Grunt 我在 grunt-ng-constant
方面取得了巨大的成功.
I'm a little late to the thread, but if you're using Grunt I've had great success with grunt-ng-constant
.
我的 Gruntfile.js
中 ngconstant
的配置部分看起来像
The config section for ngconstant
in my Gruntfile.js
looks like
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 server
将在 app/scripts/
中生成一个 config.js
文件,看起来像
So running grunt server
will generate a config.js
file in app/scripts/
that looks like
"use strict";
angular.module("config", []).constant("ENV", "development");
最后,我声明对任何需要它的模块的依赖:
Finally, I declare the dependency on whatever modules need it:
// the 'config' dependency is generated via grunt
var app = angular.module('myApp', [ 'config' ]);
现在我的常量可以在需要的地方进行依赖注入.例如,
Now my constants can be dependency injected where needed. E.g.,
app.controller('MyController', ['ENV', function( ENV ) {
if( ENV === 'production' ) {
...
}
}]);
这篇关于如何在 Angular.js 中配置不同的环境?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!