|
| 1 | +/** |
| 2 | + * Copyright (c) 2014, Facebook, Inc. All rights reserved. |
| 3 | + * |
| 4 | + * This source code is licensed under the BSD-style license found in the |
| 5 | + * LICENSE file in the root directory of this source tree. An additional grant |
| 6 | + * of patent rights can be found in the PATENTS file in the same directory. |
| 7 | + * |
| 8 | + * Adapted from node resolver: https://github.com/benmosher/eslint-plugin-import/tree/master/resolvers/node |
| 9 | + * |
| 10 | + */ |
| 11 | + |
| 12 | +'use strict'; |
| 13 | + |
| 14 | +const resolve = require('resolve'); |
| 15 | +const path = require('path'); |
| 16 | + |
| 17 | +const log = require('debug')('eslint-plugin-import:resolver:node'); |
| 18 | + |
| 19 | +module.exports.interfaceVersion = 2; |
| 20 | + |
| 21 | +module.exports.resolve = function(source, file, config) { |
| 22 | + log('Resolving:', source, 'from:', file); |
| 23 | + let resolvedPath; |
| 24 | + |
| 25 | + if (resolve.isCore(source)) { |
| 26 | + log('resolved to core'); |
| 27 | + return {found: true, path: null}; |
| 28 | + } |
| 29 | + |
| 30 | + source = applyModuleNameMapper(source, config); |
| 31 | + |
| 32 | + try { |
| 33 | + resolvedPath = resolve.sync(source, opts(file, config)); |
| 34 | + log('Resolved to:', resolvedPath); |
| 35 | + return {found: true, path: resolvedPath}; |
| 36 | + } catch (err) { |
| 37 | + log('resolve threw error:', err); |
| 38 | + return {found: false}; |
| 39 | + } |
| 40 | +}; |
| 41 | + |
| 42 | +function opts(file, config) { |
| 43 | + return Object.assign( |
| 44 | + { |
| 45 | + // more closely matches Node (#333) |
| 46 | + extensions: ['.js', '.json'], |
| 47 | + }, |
| 48 | + config, |
| 49 | + { |
| 50 | + // path.resolve will handle paths relative to CWD |
| 51 | + basedir: path.dirname(path.resolve(file)), |
| 52 | + packageFilter, |
| 53 | + } |
| 54 | + ); |
| 55 | +} |
| 56 | + |
| 57 | +function packageFilter(pkg) { |
| 58 | + if (pkg['jsnext:main']) { |
| 59 | + pkg['main'] = pkg['jsnext:main']; |
| 60 | + } |
| 61 | + return pkg; |
| 62 | +} |
| 63 | + |
| 64 | +function applyModuleNameMapper(source, config) { |
| 65 | + Object.keys(config.moduleNameMapper).forEach(regex => { |
| 66 | + const mappedModuleName = config.moduleNameMapper[regex]; |
| 67 | + |
| 68 | + if (source.match(regex)) { |
| 69 | + const matches = source.match(regex); |
| 70 | + if (!matches) { |
| 71 | + source = mappedModuleName; |
| 72 | + } else { |
| 73 | + source = mappedModuleName.replace( |
| 74 | + /\$([0-9]+)/g, |
| 75 | + (_, index) => matches[parseInt(index, 10)] |
| 76 | + ); |
| 77 | + } |
| 78 | + source = path.resolve(source); |
| 79 | + } |
| 80 | + }); |
| 81 | + |
| 82 | + return source; |
| 83 | +} |
0 commit comments