简体   繁体   中英

“Embed” a global variable in javascript file using grunt

I have a .js file in my project with code like that:

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

where API_ENDPOINT changes among dev/prod environments

It's not a js application, mostly a classic server-side app (Django) with some client-side enhacements.

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.

But I can't find a way to mangle files with 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

var API_ENDPOINT = '...';

which I will include before script.js

(Also, I'd like to "embed" this variable into my django's 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.

the folder structure could look like this:

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

some details:

  • your final clientsidecode will reside in client/dist
  • requiring a json-file will automatically parse it
  • of course you can do it with yaml/cson (see grunt-replace section )
  • dont know on how to parse a json-config in python, but it shouldn't be to difficult...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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