no-implicit-globals.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /**
  2. * @fileoverview Rule to check for implicit global variables and functions.
  3. * @author Joshua Peek
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Rule Definition
  8. //------------------------------------------------------------------------------
  9. module.exports = {
  10. meta: {
  11. docs: {
  12. description: "disallow variable and `function` declarations in the global scope",
  13. category: "Best Practices",
  14. recommended: false,
  15. url: "https://eslint.org/docs/rules/no-implicit-globals"
  16. },
  17. schema: []
  18. },
  19. create(context) {
  20. return {
  21. Program() {
  22. const scope = context.getScope();
  23. scope.variables.forEach(variable => {
  24. if (variable.writeable) {
  25. return;
  26. }
  27. variable.defs.forEach(def => {
  28. if (def.type === "FunctionName" || (def.type === "Variable" && def.parent.kind === "var")) {
  29. context.report({ node: def.node, message: "Implicit global variable, assign as global property instead." });
  30. }
  31. });
  32. });
  33. scope.implicit.variables.forEach(variable => {
  34. const scopeVariable = scope.set.get(variable.name);
  35. if (scopeVariable && scopeVariable.writeable) {
  36. return;
  37. }
  38. variable.defs.forEach(def => {
  39. context.report({ node: def.node, message: "Implicit global variable, assign as global property instead." });
  40. });
  41. });
  42. }
  43. };
  44. }
  45. };