[英]“Embed” a global variable in javascript file using grunt
我的項目中有一個.js文件,其代碼如下:
var API_ENDPOINT = 'http://example.com:8000';
var api = new RemoteApi(API_ENDPOINT);
API_ENDPOINT
在開發/產品環境之間變化的地方
它不是js應用程序,主要是帶有某些客戶端功能的經典服務器端應用程序(Django)。
我開始使用Grunt來管理客戶端依賴性,並認為,在Grunt配置中指定API_ENDPOINT
並以某種方式將其“嵌入” .js文件是個好主意。
但是我找不到用Grunt處理文件的方法。
生成的.js文件將在瀏覽器中運行,因此我需要將API_ENDPOINT
變量嵌入到API_ENDPOINT
文件中,或創建一個單獨的.js文件,例如
var API_ENDPOINT = '...';
我將在script.js之前包含
(此外,我想將此變量“嵌入”到我的Django的settings.py
)
對於客戶端js,我會將所有配置提取到config.json
文件中,並使用grunt-replace注入代碼。
文件夾結構如下所示:
- Gruntfile
- config.json
- client/
- src/
- script.js
- dist/
config.json
{
"API_ENDPOINT": "http://example.com:8000"
}
src / script.js
var API_ENDPOINT = '@@API_ENDPOINT'; // everything starting with @@ will be replaced by grunt-replace by default
var api = new RemoteApi(API_ENDPOINT);
Gruntfile
grunt.initConfig({
replace: {
dist: {
options: {
patterns: [{
json: require('config.json')
}]
},
files: [
{expand: true, flatten: true, src: ['./client/src/*.js'], dest: './client/dist/'}
]
}
}
});
一些細節:
client/dist
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.