2013-04-21 130 views
2

我正在製作一個單頁的應用程序,並與requirejs一起使用backbone。現在我想根據環境變量包含不同的配置。我不知道我該怎麼做,什麼是最佳做法。如何使用requirejs加載環境特定的配置?

我有三個不同的配置文件:

config.js:此保持常見的配置。

config.dev.js:這樣可以使開發環境的特定配置

config.production.js:這樣可以使生產的特定配置

我從擴展環境的具體型號配置模型(config.js),我需要從其他的配置模型模塊。 這工作正常,但下載dev和生產配置文件。我只想加載config.dev.js或config.production.js不是兩個。

// 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(); 

}); 

在其他模塊中我使用的配置如下樣式:

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

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

     ... 
    }); 

    return ProfileModel; 
}); 

如何加載開發或生產特定的配置文件中的一個,不是兩個?

+0

所以你的問題是,它下載這兩個文件? – Loamhoof 2013-04-21 11:59:51

+0

是的。我只需要下載。 'config.dev.js'或'config.production.js',而不是兩者。 – 2013-04-21 12:09:13

+0

也許你可以找到一種方法來使用'require',但是因爲它是異步的... – Loamhoof 2013-04-21 12:22:23

回答

3

我不知道在哪裏的ENV變量從何而來,但假設它只是一個全局變量,你可以做這樣的事情:

的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!' 
}); 

CON fig.production.js:

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

main.js:

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

我將'paths'移到'main.js'中,它仍然可以工作,所以'env.js'只包含'window.ENV =「production」;' – chovy 2013-11-26 00:23:28

相關問題