|
| 1 | +/** |
| 2 | + * @author Toru Nagashima <https://github.com/mysticatea> |
| 3 | + * See LICENSE file in root directory for full license. |
| 4 | + */ |
| 5 | +"use strict" |
| 6 | + |
| 7 | +const { findVariable } = require("eslint-utils") |
| 8 | + |
| 9 | +function isExports(node, scope) { |
| 10 | + let variable = null |
| 11 | + |
| 12 | + return ( |
| 13 | + node != null && |
| 14 | + node.type === "Identifier" && |
| 15 | + node.name === "exports" && |
| 16 | + (variable = findVariable(scope, node)) != null && |
| 17 | + variable.scope.type === "global" |
| 18 | + ) |
| 19 | +} |
| 20 | + |
| 21 | +function isModuleExports(node, scope) { |
| 22 | + let variable = null |
| 23 | + |
| 24 | + return ( |
| 25 | + node != null && |
| 26 | + node.type === "MemberExpression" && |
| 27 | + !node.computed && |
| 28 | + node.object.type === "Identifier" && |
| 29 | + node.object.name === "module" && |
| 30 | + node.property.type === "Identifier" && |
| 31 | + node.property.name === "exports" && |
| 32 | + (variable = findVariable(scope, node.object)) != null && |
| 33 | + variable.scope.type === "global" |
| 34 | + ) |
| 35 | +} |
| 36 | + |
| 37 | +module.exports = { |
| 38 | + meta: { |
| 39 | + docs: { |
| 40 | + description: "disallow the assignment to `exports`", |
| 41 | + category: "Possible Errors", |
| 42 | + recommended: false, |
| 43 | + url: |
| 44 | + "https://github.com/mysticatea/eslint-plugin-node/blob/v9.2.0/docs/rules/no-exports-assign.md", |
| 45 | + }, |
| 46 | + fixable: null, |
| 47 | + messages: { |
| 48 | + forbidden: |
| 49 | + "Unexpected assignment to 'exports' variable. Use 'module.exports' instead.", |
| 50 | + }, |
| 51 | + schema: [], |
| 52 | + type: "problem", |
| 53 | + }, |
| 54 | + create(context) { |
| 55 | + return { |
| 56 | + AssignmentExpression(node) { |
| 57 | + const scope = context.getScope() |
| 58 | + if ( |
| 59 | + !isExports(node.left, scope) || |
| 60 | + // module.exports = exports = {} |
| 61 | + (node.parent.type === "AssignmentExpression" && |
| 62 | + node.parent.right === node && |
| 63 | + isModuleExports(node.parent.left, scope)) || |
| 64 | + // exports = module.exports = {} |
| 65 | + (node.right.type === "AssignmentExpression" && |
| 66 | + isModuleExports(node.right.left, scope)) |
| 67 | + ) { |
| 68 | + return |
| 69 | + } |
| 70 | + |
| 71 | + context.report({ node, messageId: "forbidden" }) |
| 72 | + }, |
| 73 | + } |
| 74 | + }, |
| 75 | +} |
0 commit comments