1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | 'use strict';
|
7 |
|
8 | const docsUrl = require('../util/docsUrl');
|
9 | const jsxUtil = require('../util/jsx');
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | module.exports = {
|
16 | meta: {
|
17 | docs: {
|
18 | description: 'Disallow undeclared variables in JSX',
|
19 | category: 'Possible Errors',
|
20 | recommended: true,
|
21 | url: docsUrl('jsx-no-undef')
|
22 | },
|
23 | schema: [{
|
24 | type: 'object',
|
25 | properties: {
|
26 | allowGlobals: {
|
27 | type: 'boolean'
|
28 | }
|
29 | },
|
30 | additionalProperties: false
|
31 | }]
|
32 | },
|
33 |
|
34 | create(context) {
|
35 | const config = context.options[0] || {};
|
36 | const allowGlobals = config.allowGlobals || false;
|
37 |
|
38 | |
39 |
|
40 |
|
41 |
|
42 |
|
43 | function checkIdentifierInJSX(node) {
|
44 | let scope = context.getScope();
|
45 | const sourceCode = context.getSourceCode();
|
46 | const sourceType = sourceCode.ast.sourceType;
|
47 | let variables = scope.variables;
|
48 | let scopeType = 'global';
|
49 | let i;
|
50 | let len;
|
51 |
|
52 |
|
53 | if (node.name === 'this') {
|
54 | return;
|
55 | }
|
56 |
|
57 | if (!allowGlobals && sourceType === 'module') {
|
58 | scopeType = 'module';
|
59 | }
|
60 |
|
61 | while (scope.type !== scopeType) {
|
62 | scope = scope.upper;
|
63 | variables = scope.variables.concat(variables);
|
64 | }
|
65 | if (scope.childScopes.length) {
|
66 | variables = scope.childScopes[0].variables.concat(variables);
|
67 |
|
68 | if (scope.childScopes[0].childScopes.length) {
|
69 | variables = scope.childScopes[0].childScopes[0].variables.concat(variables);
|
70 | }
|
71 | }
|
72 |
|
73 | for (i = 0, len = variables.length; i < len; i++) {
|
74 | if (variables[i].name === node.name) {
|
75 | return;
|
76 | }
|
77 | }
|
78 |
|
79 | context.report({
|
80 | node,
|
81 | message: `'${node.name}' is not defined.`
|
82 | });
|
83 | }
|
84 |
|
85 | return {
|
86 | JSXOpeningElement(node) {
|
87 | switch (node.name.type) {
|
88 | case 'JSXIdentifier':
|
89 | if (jsxUtil.isDOMComponent(node)) {
|
90 | return;
|
91 | }
|
92 | node = node.name;
|
93 | break;
|
94 | case 'JSXMemberExpression':
|
95 | node = node.name;
|
96 | do {
|
97 | node = node.object;
|
98 | } while (node && node.type !== 'JSXIdentifier');
|
99 | break;
|
100 | case 'JSXNamespacedName':
|
101 | node = node.name.namespace;
|
102 | break;
|
103 | default:
|
104 | break;
|
105 | }
|
106 | checkIdentifierInJSX(node);
|
107 | }
|
108 | };
|
109 | }
|
110 | };
|