index.js 1.8 KB

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