就我个人而言,我更喜欢将其设置为构建/服务时间,因此当我更改环境时我不需要更改代码。
所以,我可以在服务器上推送并使用grunt serve:production
- 您不需要更改代码,因此您可以使用 git hooks 和 bash 脚本轻松地为您的代码提供服务。
要在 Grunt 中实现此目的,您可以使用恩古斯坦 https://github.com/werk85/grunt-ng-constant。你定义你想要的变量,它会创建一个名为 config.js (或任何你想要的)的文件,在下面公开你的变量ENV
(或任何你想要的)使用.configure()
谈论你的案例,你的 Gruntfile 中可以有这样的内容:
ngconstant: {
options: {
space: ' ',
wrap: '"use strict";\n {%= __ngModule %}',
name: 'config'
},
vagrant: {
options: {
dest: 'app/scripts/config.js'
},
constants: {
ENV: {
name: 'vagrant',
baseUrl: 'http://192.168.33.99/api/v0',
}
}
},
test: {
options: {
dest: 'app/scripts/config.js'
},
constants: {
ENV: {
name: 'test',
baseUrl: 'http://test.example.com/api/v0',
}
}
},
}
然后,在您的应用程序中,您可以使用以下命令获取 baseUrlENV.baseUrl
并公开到您的 html 文件,如下所示(角度):
app.run(function($rootScope, ENV.baseUrl){
$rootScope.baseUrl = config.baseUrl;
});
(html)
<base ng-href="{{baseUrl}}">
因此您可以使用以下方式为您的应用程序提供服务grunt serve:vagrant
当你使用 vagrant 或grunt serve:test
当你想在测试服务器上运行时