index.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use strict';
  2. const resolve = require('resolve');
  3. const isCoreModule = require('is-core-module');
  4. const path = require('path');
  5. const log = require('debug')('eslint-plugin-import:resolver:node');
  6. exports.interfaceVersion = 2;
  7. exports.resolve = function (source, file, config) {
  8. log('Resolving:', source, 'from:', file);
  9. let resolvedPath;
  10. if (isCoreModule(source)) {
  11. log('resolved to core');
  12. return { found: true, path: null };
  13. }
  14. try {
  15. const cachedFilter = function (pkg, dir) { return packageFilter(pkg, dir, config); };
  16. resolvedPath = resolve.sync(source, opts(file, config, cachedFilter));
  17. log('Resolved to:', resolvedPath);
  18. return { found: true, path: resolvedPath };
  19. } catch (err) {
  20. log('resolve threw error:', err);
  21. return { found: false };
  22. }
  23. };
  24. function opts(file, config, packageFilter) {
  25. return Object.assign({
  26. // more closely matches Node (#333)
  27. // plus 'mjs' for native modules! (#939)
  28. extensions: ['.mjs', '.js', '.json', '.node'],
  29. },
  30. config,
  31. {
  32. // path.resolve will handle paths relative to CWD
  33. basedir: path.dirname(path.resolve(file)),
  34. packageFilter,
  35. });
  36. }
  37. function identity(x) { return x; }
  38. function packageFilter(pkg, dir, config) {
  39. let found = false;
  40. const file = path.join(dir, 'dummy.js');
  41. if (pkg.module) {
  42. try {
  43. resolve.sync(String(pkg.module).replace(/^(?:\.\/)?/, './'), opts(file, config, identity));
  44. pkg.main = pkg.module;
  45. found = true;
  46. } catch (err) {
  47. log('resolve threw error trying to find pkg.module:', err);
  48. }
  49. }
  50. if (!found && pkg['jsnext:main']) {
  51. try {
  52. resolve.sync(String(pkg['jsnext:main']).replace(/^(?:\.\/)?/, './'), opts(file, config, identity));
  53. pkg.main = pkg['jsnext:main'];
  54. found = true;
  55. } catch (err) {
  56. log('resolve threw error trying to find pkg[\'jsnext:main\']:', err);
  57. }
  58. }
  59. return pkg;
  60. }