1
0

config.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /**
  2. * Wrapper around amd-config-builder.
  3. * Can be used in cli and in grunt task.
  4. */
  5. var configBuilder = require('amd-config-builder'),
  6. path = require('path'),
  7. fs = require('fs');
  8. exports.writeConfig = function (searchDir, fileForConfig, callback) {
  9. searchDir = searchDir || path.join(__dirname, '../../..');
  10. fileForConfig = fileForConfig || 'config.js';
  11. callback = callback || function (err) { if (err) throw err; };
  12. function tryToFlattenPathsMapping(mapping) {
  13. if (Array.isArray(mapping)) {
  14. for (var i = 0; i < mapping.length; ++i) {
  15. var element = mapping[i];
  16. if (element.match(/(^|:)\/\//)) break;
  17. try {
  18. var stat = fs.statSync(path.join(searchDir, element + ".js"));
  19. if (stat.isDirectory()) break;
  20. if (stat.isFile()) return element;
  21. } catch (e) {}
  22. }
  23. }
  24. return mapping;
  25. }
  26. configBuilder.produceConfigObject(searchDir, function (err, result) {
  27. if (err) return callback(err);
  28. for (var p in result.paths) {
  29. result.paths[p] = tryToFlattenPathsMapping(result.paths[p]);
  30. }
  31. var text = "/* DO NOT EDIT! This file is generated. */\n" +
  32. "\n" +
  33. "var require;\n" +
  34. "if (!require) require = {config: function (x) {require = x;}};\n" +
  35. "require.config(" + JSON.stringify(result, null, 2) + ");";
  36. fs.writeFile(path.join(searchDir, fileForConfig), text, callback);
  37. });
  38. };