visit-import.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. /**
  13. * Gets a list of `import`/`export` declaration targets.
  14. *
  15. * Core modules of Node.js (e.g. `fs`, `http`) are excluded.
  16. *
  17. * @param {RuleContext} context - The rule context.
  18. * @param {Object} [options] - The flag to include core modules.
  19. * @param {boolean} [options.includeCore] - The flag to include core modules.
  20. * @param {number} [options.optionIndex] - The index of rule options.
  21. * @param {function(ImportTarget[]):void} callback The callback function to get result.
  22. * @returns {ImportTarget[]} A list of found target's information.
  23. */
  24. module.exports = function visitImport(
  25. context,
  26. { includeCore = false, optionIndex = 0 } = {},
  27. callback
  28. ) {
  29. const targets = []
  30. const basedir = path.dirname(path.resolve(context.getFilename()))
  31. const paths = getResolvePaths(context, optionIndex)
  32. const extensions = getTryExtensions(context, optionIndex)
  33. const options = { basedir, paths, extensions }
  34. return {
  35. [[
  36. "ExportAllDeclaration",
  37. "ExportNamedDeclaration",
  38. "ImportDeclaration",
  39. "ImportExpression",
  40. ]](node) {
  41. const sourceNode = node.source
  42. // skip `import(foo)`
  43. if (
  44. node.type === "ImportExpression" &&
  45. sourceNode &&
  46. sourceNode.type !== "Literal"
  47. ) {
  48. return
  49. }
  50. const name = sourceNode && stripImportPathParams(sourceNode.value)
  51. if (name && (includeCore || !resolve.isCore(name))) {
  52. targets.push(new ImportTarget(sourceNode, name, options))
  53. }
  54. },
  55. "Program:exit"() {
  56. callback(targets)
  57. },
  58. }
  59. }