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