我个人更喜欢设置一个构建/服务时间,所以我在改变环境时不需要更改代码。
所以,我可以在服务器上推送并使用grunt serve:production - 您无需更改代码,因此您可以使用 git hooks 和 bash 脚本轻松地为您的代码提供服务。
要在 Grunt 中实现这一点,您可以使用 ngcostant。您定义所需的变量,它会创建一个名为 config.js(或任何您想要的文件)的文件,该文件使用 .configure() 在 ENV(或任何您想要的)下公开您的变量
谈到你的情况,你可以在你的 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',
}
}
},
}
然后,在您的应用中,您可以使用 ENV.baseUrl 获取 baseUrl 并暴露给您的 html 文件,如下所示(角度):
app.run(function($rootScope, ENV.baseUrl){
$rootScope.baseUrl = config.baseUrl;
});
(html)
<base ng-href="{{baseUrl}}">
因此,您可以在使用 vagrant 时使用 grunt serve:vagrant 为您的应用程序提供服务,或者在您想要在测试服务器上运行时使用 grunt serve:test 来服务您的应用程序