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