no-const-assign.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /**
  2. * @fileoverview A rule to disallow modifying variables that are declared using `const`
  3. * @author Toru Nagashima
  4. */
  5. "use strict";
  6. const astUtils = require("./utils/ast-utils");
  7. //------------------------------------------------------------------------------
  8. // Rule Definition
  9. //------------------------------------------------------------------------------
  10. module.exports = {
  11. meta: {
  12. type: "problem",
  13. docs: {
  14. description: "disallow reassigning `const` variables",
  15. category: "ECMAScript 6",
  16. recommended: true,
  17. url: "https://eslint.org/docs/rules/no-const-assign"
  18. },
  19. schema: [],
  20. messages: {
  21. const: "'{{name}}' is constant."
  22. }
  23. },
  24. create(context) {
  25. /**
  26. * Finds and reports references that are non initializer and writable.
  27. * @param {Variable} variable A variable to check.
  28. * @returns {void}
  29. */
  30. function checkVariable(variable) {
  31. astUtils.getModifyingReferences(variable.references).forEach(reference => {
  32. context.report({ node: reference.identifier, messageId: "const", data: { name: reference.identifier.name } });
  33. });
  34. }
  35. return {
  36. VariableDeclaration(node) {
  37. if (node.kind === "const") {
  38. context.getDeclaredVariables(node).forEach(checkVariable);
  39. }
  40. }
  41. };
  42. }
  43. };