index.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. function opts(file, config, packageFilter) {
  8. return Object.assign({ // more closely matches Node (#333)
  9. // plus 'mjs' for native modules! (#939)
  10. extensions: ['.mjs', '.js', '.json', '.node'],
  11. // TODO: semver-major: remove this to match Node's default behavior
  12. preserveSymlinks: true,
  13. }, config, {
  14. // path.resolve will handle paths relative to CWD
  15. basedir: path.dirname(path.resolve(file)),
  16. packageFilter,
  17. });
  18. }
  19. function identity(x) { return x; }
  20. function packageFilter(pkg, dir, config) {
  21. let found = false;
  22. const file = path.join(dir, 'dummy.js');
  23. if (pkg.module) {
  24. try {
  25. resolve(String(pkg.module).replace(/^(?:\.\/)?/, './'), opts(file, config, identity));
  26. pkg.main = pkg.module;
  27. found = true;
  28. } catch (err) {
  29. log('resolve threw error trying to find pkg.module:', err);
  30. }
  31. }
  32. if (!found && pkg['jsnext:main']) {
  33. try {
  34. resolve(String(pkg['jsnext:main']).replace(/^(?:\.\/)?/, './'), opts(file, config, identity));
  35. pkg.main = pkg['jsnext:main'];
  36. found = true;
  37. } catch (err) {
  38. log('resolve threw error trying to find pkg[\'jsnext:main\']:', err);
  39. }
  40. }
  41. return pkg;
  42. }
  43. exports.resolve = function (source, file, config) {
  44. log('Resolving:', source, 'from:', file);
  45. let resolvedPath;
  46. if (isCoreModule(source)) {
  47. log('resolved to core');
  48. return { found: true, path: null };
  49. }
  50. try {
  51. const cachedFilter = function (pkg, pkgFileOrDir, maybeDir) { return packageFilter(pkg, maybeDir || pkgFileOrDir, config); };
  52. resolvedPath = resolve(source, opts(file, config, cachedFilter));
  53. log('Resolved to:', resolvedPath);
  54. return { found: true, path: resolvedPath };
  55. } catch (err) {
  56. log('resolve threw error:', err);
  57. return { found: false };
  58. }
  59. };