index.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. var path = require('path');
  2. var extension = require('./lib/extension');
  3. var normalize = require('./lib/normalize');
  4. var register = require('./lib/register');
  5. exports.prepare = function(extensions, filepath, cwd, nothrow) {
  6. var config, usedExtension, err, option, attempt, error;
  7. var attempts = [];
  8. var onlyErrors = true;
  9. var exts = extension(filepath);
  10. if (exts) {
  11. exts.some(function(ext) {
  12. usedExtension = ext;
  13. config = normalize(extensions[ext]);
  14. return !!config;
  15. });
  16. }
  17. if (Object.keys(require.extensions).indexOf(usedExtension) !== -1) {
  18. return true;
  19. }
  20. if (!config) {
  21. if (nothrow) {
  22. return;
  23. }
  24. throw new Error('No module loader found for "' + usedExtension + '".');
  25. }
  26. if (!cwd) {
  27. cwd = path.dirname(path.resolve(filepath));
  28. }
  29. if (!Array.isArray(config)) {
  30. config = [config];
  31. }
  32. for (var i in config) {
  33. option = config[i];
  34. attempt = register(cwd, option.module, option.register);
  35. error = (attempt instanceof Error) ? attempt : null;
  36. if (error) {
  37. attempt = null;
  38. }
  39. attempts.push({
  40. moduleName: option.module,
  41. module: attempt,
  42. error: error,
  43. });
  44. if (!error) {
  45. onlyErrors = false;
  46. break;
  47. }
  48. }
  49. if (onlyErrors) {
  50. err = new Error('Unable to use specified module loaders for "' + usedExtension + '".');
  51. err.failures = attempts;
  52. if (nothrow) {
  53. return err;
  54. }
  55. throw err;
  56. }
  57. return attempts;
  58. };