1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | 'use strict';
|
7 |
|
8 | const path = require('path');
|
9 | const docsUrl = require('../util/docsUrl');
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | const DEFAULTS = {
|
16 | extensions: ['.jsx']
|
17 | };
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 | module.exports = {
|
24 | meta: {
|
25 | docs: {
|
26 | description: 'Restrict file extensions that may contain JSX',
|
27 | category: 'Stylistic Issues',
|
28 | recommended: false,
|
29 | url: docsUrl('jsx-filename-extension')
|
30 | },
|
31 |
|
32 | schema: [{
|
33 | type: 'object',
|
34 | properties: {
|
35 | extensions: {
|
36 | type: 'array',
|
37 | items: {
|
38 | type: 'string'
|
39 | }
|
40 | }
|
41 | },
|
42 | additionalProperties: false
|
43 | }]
|
44 | },
|
45 |
|
46 | create(context) {
|
47 | let invalidExtension;
|
48 | let invalidNode;
|
49 |
|
50 | function getExtensionsConfig() {
|
51 | return context.options[0] && context.options[0].extensions || DEFAULTS.extensions;
|
52 | }
|
53 |
|
54 | function handleJSX(node) {
|
55 | const filename = context.getFilename();
|
56 | if (filename === '<text>') {
|
57 | return;
|
58 | }
|
59 |
|
60 | if (invalidNode) {
|
61 | return;
|
62 | }
|
63 |
|
64 | const allowedExtensions = getExtensionsConfig();
|
65 | const isAllowedExtension = allowedExtensions.some((extension) => filename.slice(-extension.length) === extension);
|
66 |
|
67 | if (isAllowedExtension) {
|
68 | return;
|
69 | }
|
70 |
|
71 | invalidNode = node;
|
72 | invalidExtension = path.extname(filename);
|
73 | }
|
74 |
|
75 |
|
76 |
|
77 |
|
78 |
|
79 | return {
|
80 | JSXElement: handleJSX,
|
81 | JSXFragment: handleJSX,
|
82 |
|
83 | 'Program:exit'() {
|
84 | if (!invalidNode) {
|
85 | return;
|
86 | }
|
87 |
|
88 | context.report({
|
89 | node: invalidNode,
|
90 | message: `JSX not allowed in files with extension '${invalidExtension}'`
|
91 | });
|
92 | }
|
93 | };
|
94 | }
|
95 | };
|