根据环境在angularjs项目中设置基本URL [英] Set base URL in angularjs project based on the environment
问题描述
我正在使用Yeoman创建一个AngularJs项目。该项目使用Grunt作为任务管理器。
I'm working on an AngularJs project created using Yeoman. The project uses Grunt as task manager.
在我的index.html中,我需要设置基本URL:
In my index.html I need to set the base url:
<base href="/">
href属性值取决于环境:如果环境是开发环境,我希望href只是 /
,如果环境是生产环境,则值必须为 a / b / c
。
The href attribute value depends on the environment: if the environment is development I want href to be simply /
, if the environment is production the value has to be something else a/b/c
.
有什么解决方案?
可以使用AngualrJs中的常量在运行时动态设置它最好在构建/服务时间静态设置它?
It is possible to set it dynamically at runtime using a constant from AngualrJs or it is better to set it statically at build/serve time?
推荐答案
我个人更喜欢将其设置为构建/服务时间,所以更改环境时不需要更改代码。
Personally I prefer to set it a build/serve time, so I don't need to change the code when I change environment.
因此,我可以在服务器上推送并使用 grunt serve:production
-无需更改代码,因此可以使用git hook和bash脚本轻松提供代码。
So, I can push on the server and use grunt serve:production
- you don't need to change the code, so you can use git hooks and a bash script to easily serve your code.
在Grunt中,您可以使用 ngcostant 。您定义所需的变量,并创建一个名为config.js(或任何您想要的变量)的文件,该文件使用<$将您的变量暴露在 ENV
(或您想要的变量)下c $ c> .configure()
To achieve this in Grunt you can use ngcostant. You define the vars you want, and it creates a file named config.js (or whatever you want) that exposes your vars under ENV
(or whatever you want) using .configure()
谈谈您的案子,您可以在Gruntfile中输入以下内容:
Talking about your case, you can have something like this in your 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文件中,如下所示(角度):
Then, in your app you can take the baseUrl using ENV.baseUrl
and expose to your html file, like this (angular):
app.run(function($rootScope, ENV.baseUrl){
$rootScope.baseUrl = config.baseUrl;
});
(html)
<base ng-href="{{baseUrl}}">
因此,您可以使用 grunt serve:vagrant $ c服务您的应用程序$ c>使用无业游民或
grunt serve:test
想要在测试服务器上运行时
So you can serve your application using grunt serve:vagrant
when you're using vagrant or grunt serve:test
when you want to run on your test server
这篇关于根据环境在angularjs项目中设置基本URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!