get-import-export-targets.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * @author Toru Nagashima
  3. * See LICENSE file in root directory for full license.
  4. */
  5. "use strict"
  6. const path = require("path")
  7. const resolve = require("resolve")
  8. const getResolvePaths = require("./get-resolve-paths")
  9. const getTryExtensions = require("./get-try-extensions")
  10. const ImportTarget = require("./import-target")
  11. const stripImportPathParams = require("./strip-import-path-params")
  12. const MODULE_TYPE = /^(?:Import|Export(?:Named|Default|All))Declaration$/u
  13. /**
  14. * Gets a list of `import`/`export` declaration targets.
  15. *
  16. * Core modules of Node.js (e.g. `fs`, `http`) are excluded.
  17. *
  18. * @param {RuleContext} context - The rule context.
  19. * @param {ASTNode} programNode - The node of Program.
  20. * @param {boolean} includeCore - The flag to include core modules.
  21. * @returns {ImportTarget[]} A list of found target's information.
  22. */
  23. module.exports = function getImportExportTargets(
  24. context,
  25. programNode,
  26. includeCore
  27. ) {
  28. const retv = []
  29. const basedir = path.dirname(path.resolve(context.getFilename()))
  30. const paths = getResolvePaths(context)
  31. const extensions = getTryExtensions(context)
  32. const options = { basedir, paths, extensions }
  33. for (const statement of programNode.body) {
  34. // Skip if it's not a module declaration.
  35. if (!MODULE_TYPE.test(statement.type)) {
  36. continue
  37. }
  38. // Gets the target module.
  39. const node = statement.source
  40. const name = node && stripImportPathParams(node.value)
  41. if (name && (includeCore || !resolve.isCore(name))) {
  42. retv.push(new ImportTarget(node, name, options))
  43. }
  44. }
  45. return retv
  46. }