index.js 1.3 KB

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