简体   繁体   English

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

[英]“Embed” a global variable in javascript file using grunt

I have a .js file in my project with code like that: 我的项目中有一个.js文件,其代码如下:

var API_ENDPOINT = 'http://example.com:8000';
var api = new RemoteApi(API_ENDPOINT);

where API_ENDPOINT changes among dev/prod environments API_ENDPOINT在开发/产品环境之间变化的地方

It's not a js application, mostly a classic server-side app (Django) with some client-side enhacements. 它不是js应用程序,主要是带有某些客户端功能的经典服务器端应用程序(Django)。

I started using Grunt for managing client-side dependencies and thought, it'd be a good idea to specify API_ENDPOINT in Grunt config and somehow "embed" it into .js file. 我开始使用Grunt来管理客户端依赖性,并认为,在Grunt配置中指定API_ENDPOINT并以某种方式将其“嵌入” .js文件是个好主意。

But I can't find a way to mangle files with Grunt. 但是我找不到用Grunt处理文件的方法。

The resulting .js file will be run in browser envorenment, so I need my API_ENDPOINT variable embedded in source.js file or creating a separate .js file like 生成的.js文件将在浏览器中运行,因此我需要将API_ENDPOINT变量嵌入到API_ENDPOINT文件中,或创建一个单独的.js文件,例如

var API_ENDPOINT = '...';

which I will include before script.js 我将在script.js之前包含

(Also, I'd like to "embed" this variable into my django's settings.py ) (此外,我想将此变量“嵌入”到我的Django的settings.py

for the clientside js i would extract all configs into a config.json file, and use grunt-replace for injection to your code. 对于客户端js,我会将所有配置提取到config.json文件中,并使用grunt-replace注入代码。

the folder structure could look like this: 文件夹结构如下所示:

- Gruntfile
- config.json
- client/
  - src/
    - script.js
  - dist/      

config.json config.json

{
  "API_ENDPOINT": "http://example.com:8000"
}

src/script.js 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 Gruntfile

grunt.initConfig({
  replace: {
    dist: {
      options: {
        patterns: [{
         json: require('config.json')
        }]
      },
      files: [
        {expand: true, flatten: true, src: ['./client/src/*.js'], dest: './client/dist/'}
      ]
    }
  }
});

some details: 一些细节:

  • your final clientsidecode will reside in client/dist 您的最终clientsidecode将驻留在client/dist
  • requiring a json-file will automatically parse it 需要一个json文件将自动解析它
  • of course you can do it with yaml/cson (see grunt-replace section ) 当然,您可以使用yaml / cson来做到这一点(请参阅grunt-replace部分
  • dont know on how to parse a json-config in python, but it shouldn't be to difficult... 不知道如何在python中解析json-config,但这并不难...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM