index.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. 'use strict';
  2. const resolve = require('resolve/sync');
  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(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({ // more closely matches Node (#333)
  26. // plus 'mjs' for native modules! (#939)
  27. extensions: ['.mjs', '.js', '.json', '.node'],
  28. }, config, {
  29. // path.resolve will handle paths relative to CWD
  30. basedir: path.dirname(path.resolve(file)),
  31. packageFilter,
  32. });
  33. }
  34. function identity(x) { return x; }
  35. function packageFilter(pkg, dir, config) {
  36. let found = false;
  37. const file = path.join(dir, 'dummy.js');
  38. if (pkg.module) {
  39. try {
  40. resolve(String(pkg.module).replace(/^(?:\.\/)?/, './'), opts(file, config, identity));
  41. pkg.main = pkg.module;
  42. found = true;
  43. } catch (err) {
  44. log('resolve threw error trying to find pkg.module:', err);
  45. }
  46. }
  47. if (!found && pkg['jsnext:main']) {
  48. try {
  49. resolve(String(pkg['jsnext:main']).replace(/^(?:\.\/)?/, './'), opts(file, config, identity));
  50. pkg.main = pkg['jsnext:main'];
  51. found = true;
  52. } catch (err) {
  53. log('resolve threw error trying to find pkg[\'jsnext:main\']:', err);
  54. }
  55. }
  56. return pkg;
  57. }