Turn json file into js object.
If you used to
var socket = io.connect('http://localhost:5000'); // dev environment
and
var socket = io.connect('http://172.18.3.24:5033'); // prod environment
well... you deserve to have
// resources/config.json
{
"dev": {
"api": "http://localhost:5000"
},
"prod": {
"api": "http://172.18.3.24:5033"
}
}
and use it like that
var socket = io.connect(Config.api); // dev or prod - who cares
This plugin requires Grunt ~0.4.2
If you haven't used Grunt before, be sure to check out the Getting Started guide, as it explains how to create a Gruntfile as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:
npm install grunt-variablize --save-dev
Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:
grunt.loadNpmTasks('grunt-variablize');
In your project's Gruntfile, add a section named variablize
to the data object passed into grunt.initConfig()
.
grunt.initConfig({
variablize: {
your_target: {
// Target-specific options go here.
}
}
});
Type: String
Path to json file.
Type: String
Path to output js file.
Type: String
Variable name to use.
Type: String
Json property name which should be variablized.
In this example, the whole resources/Config.json
file is used to create dist/Config.js
.
// resources/Config.json
{
"foo": "bar"
}
// dist/Config.js
var Config = {"foo":"bar"};
grunt.initConfig({
variablize: {
basic: {
input: "resources/Config.json",
output: "dist/Config.js",
variable: "Config"
}
}
});
In this example, property
is used to filter json file.
// input file - resources/Config.json
{
"dev": {
"serviceUrl": "http://dev.my.service/"
},
"test": {
"serviceUrl": "http://test.my.service/"
},
"prod": {
"serviceUrl": "http://prod.my.service/"
}
}
// output file - dist/Config.js
var Config = {"serviceUrl":"http://prod.my.service/"};
grunt.initConfig({
variablize: {
prod: {
input: "resources/Config.json",
output: "dist/Config.js",
variable: "Config",
property: "prod"
}
}
});