我有一個web應用程序(emberjs),我需要根據grunt任務設置env變量。所以當我運行grunt server
時,它會選擇development
,url將被設置爲localhost:5000
。但是當我做grunt build
,它會選擇production
和URL將被設置爲production.com
。基於grunt任務設置env變量
主要的問題對我來說是,如何讀取燼這些變量。或如何使繁重的神色一變,並改變它基於任務
是否有可能做這樣的事情?
我有一個web應用程序(emberjs),我需要根據grunt任務設置env變量。所以當我運行grunt server
時,它會選擇development
,url將被設置爲localhost:5000
。但是當我做grunt build
,它會選擇production
和URL將被設置爲production.com
。基於grunt任務設置env變量
主要的問題對我來說是,如何讀取燼這些變量。或如何使繁重的神色一變,並改變它基於任務
是否有可能做這樣的事情?
經過大量的谷歌搜索和沒有很好的例子,這是我做的。
假設您使用yeoman腳手架yo ember
生成器並使用grunt build
來構建dist。
喲燼生成器v0.8使用咕嚕替換。升級到該版本。總之,我使用grunt-replace將全局變量添加到index.html。就是這樣。
的聯合scripts.js中塊之前,這個腳本標籤添加到應用程序/ index.html的:
#app/index.html
<script>
/*
simplify grunt-replace strategy by placing env vars here.
*/
window.MYCOMPANYCOM_ENV = {
env: '@@env',
apiHost: '@@apiHost'
};
</script>
/* ADD THE ABOVE BEFORE THIS SECTION */
<!-- build:js(.tmp) scripts/main.js -->
<script src="scripts/combined-scripts.js"></script>
<!-- endbuild -->
並更改Gruntfile.js這個替換配置:
module.exports = function (grunt) {
var appConfig = grunt.file.readJSON('app_config.json');
replace: {
app: {
options: {
patterns: [
{
json: appConfig['app']
}
]
},
files: [
{src: '<%= yeoman.app %>/index.html', dest: '.tmp/index.html'}
]
},
dist: {
options: {
patterns: [
{
json: appConfig['dist']
}
]
},
files: [
{src: '<%= yeoman.dist %>/index.html', dest: '<%= yeoman.dist %>/index.html'}
]
}
}
創建./app_config.json上的新文件
{
"app": {
"env": "development",
"apiHost": "http://localhost:8080"
},
"dist": {
"env": "dist",
"apiHost": "/"
}
}
現在,您的應用程序腳本可以訪問app_中定義的全局變量config.json。
我不會進入更詳細,但是這個工作正常發展。對於grunt build
,我將replace:dist
步驟移至構建步驟的末尾,並將index.html中的@@ ember變量替換爲bower組件的路徑。
是的,這是可能的。使用grunt-env
指定您的環境,並結合grunt-usemin
之類的內容將您的環境變量公開給您的應用程序代碼。
根據this SO thread你需要確保你的環境變量之前Ember.js加載。
我在emberjs之前設置了一個可用的ENV變量,而grunt-env似乎很適合在那裏定義變量。但是如何匹配grunt-env變量以便在我選擇的地方設置。有沒有找到和替換的方法?在構建或運行服務器之前,如何將變量放在特定位置? –
請參閱[本SO線程]中的答案(http://stackoverflow.com/questions/12401998/have-grunt-generate-index-html-for-different-setups)。根據我的回答,我建議你使用像''grunt-usemin'](https://npmjs.org/package/grunt-usemin)這樣的暴露你的環境變量到你的應用程序,但如果你看看[線程我鏈接](http://stackoverflow.com/questions/12401998/have-grunt-generate-index-html-for-different-setups)你可以看到有更多的方法來剝皮這隻貓。 –