I am currently working myself into requirejs, to do this I started to write a small package. The package consists of one main.js, the entry point for the application and several other modules that will be loaded into main.js through a call to require.
The package has several options that can be configured during runtime, to ease maintenance I have a central configuration.js that is loaded whenever needed. The contents of configuration.js is just an object that maps key to value, no functionality or anything. Just a key-value map.
Now requirejs allows to pass options to packages, the configuration is done through the requirejs config. The problem I have is, that it is only available in the main.js and not in other modules in the package, also I could not find a way to set default values unless I hardcode them into the main.js.
My current approach (the one with the configuration.js) is to merge the configuration given to requirejs with the contents of my configuration.js in the main.js.
main.js
define(function(require, exports, module) {
var $ = require('jquery'); // Could be any library that offers an "extend"
// feature that allows "deep" copies.
var config = require('configuration'); // Load configuration file
$.extend(true, config, module.config()); // Overwrite default values with
// set values
var otherfile = require('anyotherfile);
otherfile();
});
anyotherfile.js
define(function(require, exports, module) {
var config = require('config'); // Loads configuration, package-wide
// options are set
// module.config() will be empty. Unless I explicicy specify the
// configuration for this one module in the "requirejs.config"
return function() {
// Something that can be configured
};
});
This way of setting configuration options makes me dependent on an additional library or my own implementation of an extend functionality (it’s not much code, but still more code than no code) plus there are two points where I have to look for possible configuration mistakes which makes it harder to find errors.
So now I am searching for a better way to pass a package-wide configuration all while trying to avoid more than one point of failure. (This might be hard cause somewhere I have to store the default values if I don’t want to hardcode them.) And of course the solution should not depend on any additional libraries or my own extend functionality.
After talking with jrburke about the problem the best solution is to do the extending of the config array in the
configuration.js.Example of the file
configuration.jsSo there is no more need to do this in the
main.js.The only disadvantage of this approach is that in the
requirejs.configyou have to addresspackage/configurationand notpackage.Example of the
requirejs.config