簡體   English   中英

使用grunt“嵌入” JavaScript文件中的全局變量

[英]“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/'}
      ]
    }
  }
});

一些細節:

  • 您的最終clientsidecode將駐留在client/dist
  • 需要一個json文件將自動解析它
  • 當然,您可以使用yaml / cson來做到這一點(請參閱grunt-replace部分
  • 不知道如何在python中解析json-config,但這並不難...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM