项目原始demo,不改动
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

global-require.js 2.2 KiB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /**
  2. * @fileoverview Rule for disallowing require() outside of the top-level module context
  3. * @author Jamund Ferguson
  4. */
  5. "use strict";
  6. const ACCEPTABLE_PARENTS = [
  7. "AssignmentExpression",
  8. "VariableDeclarator",
  9. "MemberExpression",
  10. "ExpressionStatement",
  11. "CallExpression",
  12. "ConditionalExpression",
  13. "Program",
  14. "VariableDeclaration"
  15. ];
  16. /**
  17. * Finds the eslint-scope reference in the given scope.
  18. * @param {Object} scope The scope to search.
  19. * @param {ASTNode} node The identifier node.
  20. * @returns {Reference|null} Returns the found reference or null if none were found.
  21. */
  22. function findReference(scope, node) {
  23. const references = scope.references.filter(reference => reference.identifier.range[0] === node.range[0] &&
  24. reference.identifier.range[1] === node.range[1]);
  25. /* istanbul ignore else: correctly returns null */
  26. if (references.length === 1) {
  27. return references[0];
  28. }
  29. return null;
  30. }
  31. /**
  32. * Checks if the given identifier node is shadowed in the given scope.
  33. * @param {Object} scope The current scope.
  34. * @param {ASTNode} node The identifier node to check.
  35. * @returns {boolean} Whether or not the name is shadowed.
  36. */
  37. function isShadowed(scope, node) {
  38. const reference = findReference(scope, node);
  39. return reference && reference.resolved && reference.resolved.defs.length > 0;
  40. }
  41. module.exports = {
  42. meta: {
  43. docs: {
  44. description: "require `require()` calls to be placed at top-level module scope",
  45. category: "Node.js and CommonJS",
  46. recommended: false,
  47. url: "https://eslint.org/docs/rules/global-require"
  48. },
  49. schema: []
  50. },
  51. create(context) {
  52. return {
  53. CallExpression(node) {
  54. const currentScope = context.getScope();
  55. if (node.callee.name === "require" && !isShadowed(currentScope, node.callee)) {
  56. const isGoodRequire = context.getAncestors().every(parent => ACCEPTABLE_PARENTS.indexOf(parent.type) > -1);
  57. if (!isGoodRequire) {
  58. context.report({ node, message: "Unexpected require()." });
  59. }
  60. }
  61. }
  62. };
  63. }
  64. };