get-import-export-targets.js 2.2 KB

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