2 * @fileoverview Rule to flag use of console object
3 * @author Nicholas C. Zakas
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
12 const astUtils = require("./utils/ast-utils");
14 //------------------------------------------------------------------------------
16 //------------------------------------------------------------------------------
23 description: "disallow the use of `console`",
24 category: "Possible Errors",
26 url: "https://eslint.org/docs/rules/no-console"
42 additionalProperties: false
47 unexpected: "Unexpected console statement."
52 const options = context.options[0] || {};
53 const allowed = options.allow || [];
56 * Checks whether the given reference is 'console' or not.
57 * @param {eslint-scope.Reference} reference The reference to check.
58 * @returns {boolean} `true` if the reference is 'console'.
60 function isConsole(reference) {
61 const id = reference.identifier;
63 return id && id.name === "console";
67 * Checks whether the property name of the given MemberExpression node
68 * is allowed by options or not.
69 * @param {ASTNode} node The MemberExpression node to check.
70 * @returns {boolean} `true` if the property name of the node is allowed.
72 function isAllowed(node) {
73 const propertyName = astUtils.getStaticPropertyName(node);
75 return propertyName && allowed.indexOf(propertyName) !== -1;
79 * Checks whether the given reference is a member access which is not
80 * allowed by options or not.
81 * @param {eslint-scope.Reference} reference The reference to check.
82 * @returns {boolean} `true` if the reference is a member access which
83 * is not allowed by options.
85 function isMemberAccessExceptAllowed(reference) {
86 const node = reference.identifier;
87 const parent = node.parent;
90 parent.type === "MemberExpression" &&
91 parent.object === node &&
97 * Reports the given reference as a violation.
98 * @param {eslint-scope.Reference} reference The reference to report.
101 function report(reference) {
102 const node = reference.identifier.parent;
107 messageId: "unexpected"
113 const scope = context.getScope();
114 const consoleVar = astUtils.getVariableByName(scope, "console");
115 const shadowed = consoleVar && consoleVar.defs.length > 0;
118 * 'scope.through' includes all references to undefined
119 * variables. If the variable 'console' is not defined, it uses
122 const references = consoleVar
123 ? consoleVar.references
124 : scope.through.filter(isConsole);
128 .filter(isMemberAccessExceptAllowed)