我正在尝试使 angularjs 应用程序在配置( http://12factor.net/config )方面符合 12 因素。
它应该取决于环境,我不应该看到 development
字样, test
, production
等在代码中。
变量可以存储在 bash env
例如。
我可以将它们传递给网络服务器。
我已经想到了一个 .erb 模板文件到 erb config.js.erb > config.js
,但是如果我在应用程序运行时更改变量,我必须重做。
我已经找到这篇文章 http://mindthecode.com/how-to-use-environment-variables-in-your-angular-application/
但这是一个很大的谎言,而且 Grunt.js 这样做,真的......无论如何。
我知道 12factor 哲学不是为前端应用程序而制定的,但我的 Angular 应用程序可以部署在许多环境中的许多不同服务器中,并且尝试正确地做事不会伤害任何人:)。
谢谢 !
编辑:
我想使用的配置参数是这样的:
app:
api:
url: "The url of the api server"
port: 8080
cdn:
images: "url of my images caching service"
google:
oauth:
"api_key": "The api key used for that deployment"
#other external frontend services
其他编辑:
这家伙有点回答:http://bahmutov.calepin.co/inject-valid-constants-into-angular.html我觉得有点难看,完全与 angularjs 绑定(bind);但它有效!
最佳答案
这是我找到的解决方案,它完全绑定(bind)到 angularjs,但它在 Heroku 上对我有用,而且非常简单。我只是将我的 conf 模块附加到生成的代码中。
每次我重新启动应用程序时,都会复制新版本的代码,因此 Append
只发生一次。Append
只是重新定义一个已经存在的配置变量。
如果有人找到更“优雅”的东西,我很乐意将其作为正确的解决方案!
var compression = require('compression');
var express = require('express');
var logfmt = require('logfmt');
var stdio = require('stdio');
var glob = require("glob");
var fs = require('fs');
// ------------------------
// Read config from args
var ops = stdio.getopt({
'url': {
key: 'u',
args: 1,
default: '',
description: 'Url of api server'
},
'port': {
key: 'p',
args: 1,
default: 5000,
description: 'Port on which to listen'
}
});
var port = ops.port || process.env.PORT;
ops.port = undefined;
// ------------------------
// Append config to js built file
var codeToAppend = 'angular.module("project.config",[]).constant("ApiConfig",' + JSON.stringify(ops) + ');';
glob(__dirname + '/dist/scripts/scripts.*.js', function(er, files) {
fs.appendFile(files[0], codeToAppend, function(err) {
if (err) {
throw err;
}
console.log('The "conf code" was appended to file!');
});
});
// ------------------------
// Start App :3
var app = express();
app.use(logfmt.requestLogger());
app.use(compression({
threshold: 512
}));
app.use(express.static(__dirname + '/dist'));
app.get('/config', function(req, res) {
res.json(ops);
});
app.listen(port);
关于angularjs - 如何使 angularjs 应用程序在配置方面符合 12 因素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23952152/