I am writing the javascript, AngularJS app using typescript. Also I am using grunt for building. In fact I have started off with ng boilerplate.
Now suppose I have a config.json
file something like below-
{
"app": "abc",
"login": "xyz"
}
I want some variables in my app to be configurable. So at some place I could use something like -
var loginUrl : string = "def?pqr="+config.app;
Now how can I read this config in my javascript files? I am looking for best practice answer. I am fine with substitution at grunt build
step also.
Note: The config file is present on client itself, i.e no need to load it from server separately.
In the Project Explorer view, expand the plug-in project node. Expand the plugin folder node. Double-click the config. json file, or right-click the file and select Open with > PDK JSON Editor.
The angular. json file at the root level of an Angular workspace provides workspace-wide and project-specific configuration defaults. These are used for build and development tools provided by the Angular CLI. Path values given in the configuration are relative to the root workspace directory.
In my case, I use grunt to inject a config file (shared with the server) in an angular constant module :
Using grunt-preprocess :
I having a config.tpl.js with :
angular.module('app.config', [])
.constant('appConfig', {
// clientside specific constants
var1 : 'value1',
var2 : [1,2,3],
sharedVars : /* @echo SHARED_VARS */
});
Then, in my gruntFile :
preprocess: {
options: {
context: {
SHARED_VARS: grunt.file.read('config.json'),
}
},
config: {
src: 'src/config.tpl.js',
dest: 'src/config.js' // true file generated and loaded in index.html
}
},
That way you can inject a full config file in an angular constant module, or pick only the vars you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With