2
votes

I am making a single page app and using backbone with requirejs. Now I want to include different configurations depending environment variable. I don't know how can I do this and what is best practices.

I have three different config file:

config.js : This keep common configurations.

config.dev.js : This keeps development environment specific configurations

config.production.js : This keeps production specific configurations

I am extending Config model(in config.js) from environment specific model and I requiring the Config model from other modules. This working fine but downloading dev and production config files both. I want only load config.dev.js or config.production.js not both.

// config.js
define([
  'backbone',
  'modules/config/config.dev',
  'modules/config/config.production'
], function(Backbone, DevConfig, ProdConfig) {

    // Select environment model
    EnvConfig = (ENV == 'dev') ? DevConfig : ProdConfig;

    var ConfigModel = EnvConfig.extend({
        // Extending attributes.
        defaults: _.extend({
           foo : 'bar'
        }, EnvConfig.prototype.defaults)

    });

    return new ConfigModel();

});

In other modules I am using Config as below style:

define([
    'backbone',
    'modules/config/config'
], function(Backbone, Config) {

    var ProfileModel = Backbone.Model.extend({
        urlRoot: Config.get('apiRoot') + '/profiles'

        ...
    });

    return ProfileModel;
});

How to load one of development or production specific config file, not both?

1
So your problem is that it downloads both files?Loamhoof
Yes. I want download only required. config.dev.js or config.production.js, not both.Mesut Tasci
Perhaps you could find a way to use require but as it is async...Loamhoof
How can I return Config Model with require?. I am trying with require but define return undifened from module because async.Mesut Tasci

1 Answers

3
votes

I'm not sure where the ENV variable comes from, but assuming it's just a global variable you could do something like this:

index.html

<script type="text/javascript">
    // adding it here so the example works on its own
    window.ENV = 'production'; // or 'dev'
    // this will be added to RequireJS configuration
    var require = {
      paths: {
        // 'env-config' will be an alias for actual file name
        'env-config': 'config.' + window.ENV
      }
    };
</script>
<script data-main="scripts/main" src="scripts/requirejs.js"></script>

config.dev.js:

define({
    'env': 'development!'
}); 

config.production.js:

define({
    'env': 'production!'
}); 

main.js:

require(['config', 'env-config'], function(conf, envConfig) {
   console.log('The environment is: ', envConfig.env);
});