visit-require.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 { CALL, ReferenceTracker, getStringIfConstant } = require("eslint-utils")
  8. const resolve = require("resolve")
  9. const getResolvePaths = require("./get-resolve-paths")
  10. const getTryExtensions = require("./get-try-extensions")
  11. const ImportTarget = require("./import-target")
  12. const stripImportPathParams = require("./strip-import-path-params")
  13. /**
  14. * Gets a list of `require()` targets.
  15. *
  16. * Core modules of Node.js (e.g. `fs`, `http`) are excluded.
  17. *
  18. * @param {RuleContext} context - The rule context.
  19. * @param {Object} [options] - The flag to include core modules.
  20. * @param {boolean} [options.includeCore] - The flag to include core modules.
  21. * @param {function(ImportTarget[]):void} callback The callback function to get result.
  22. * @returns {Object} The visitor.
  23. */
  24. module.exports = function visitRequire(
  25. context,
  26. { includeCore = false } = {},
  27. callback
  28. ) {
  29. const targets = []
  30. const basedir = path.dirname(path.resolve(context.getFilename()))
  31. const paths = getResolvePaths(context)
  32. const extensions = getTryExtensions(context)
  33. const options = { basedir, paths, extensions }
  34. return {
  35. "Program:exit"() {
  36. const tracker = new ReferenceTracker(context.getScope())
  37. const references = tracker.iterateGlobalReferences({
  38. require: {
  39. [CALL]: true,
  40. resolve: { [CALL]: true },
  41. },
  42. })
  43. for (const { node } of references) {
  44. const targetNode = node.arguments[0]
  45. const rawName = getStringIfConstant(targetNode)
  46. const name = rawName && stripImportPathParams(rawName)
  47. if (name && (includeCore || !resolve.isCore(name))) {
  48. targets.push(new ImportTarget(targetNode, name, options))
  49. }
  50. }
  51. callback(targets)
  52. },
  53. }
  54. }