-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
no-commonjs.js
116 lines (95 loc) · 2.93 KB
/
no-commonjs.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/**
* @fileoverview Rule to prefer ES6 to CJS
* @author Jamund Ferguson
*/
import docsUrl from '../docsUrl'
const EXPORT_MESSAGE = 'Expected "export" or "export default"'
, IMPORT_MESSAGE = 'Expected "import" instead of "require()"'
function normalizeLegacyOptions(options) {
if (options.indexOf('allow-primitive-modules') >= 0) {
return { allowPrimitiveModules: true }
}
return options[0] || {}
}
function allowPrimitive(node, options) {
if (!options.allowPrimitiveModules) return false
if (node.parent.type !== 'AssignmentExpression') return false
return (node.parent.right.type !== 'ObjectExpression')
}
function allowRequire(node, options) {
return options.allowRequire
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
const schemaString = { enum: ['allow-primitive-modules'] }
const schemaObject = {
type: 'object',
properties: {
allowPrimitiveModules: { 'type': 'boolean' },
allowRequire: { 'type': 'boolean' },
},
additionalProperties: false,
}
module.exports = {
meta: {
type: 'suggestion',
docs: {
url: docsUrl('no-commonjs'),
},
schema: {
anyOf: [
{
type: 'array',
items: [schemaString],
additionalItems: false,
},
{
type: 'array',
items: [schemaObject],
additionalItems: false,
},
],
},
},
create: function (context) {
const options = normalizeLegacyOptions(context.options)
return {
'MemberExpression': function (node) {
// module.exports
if (node.object.name === 'module' && node.property.name === 'exports') {
if (allowPrimitive(node, options)) return
context.report({ node, message: EXPORT_MESSAGE })
}
// exports.
if (node.object.name === 'exports') {
const isInScope = context.getScope()
.variables
.some(variable => variable.name === 'exports')
if (! isInScope) {
context.report({ node, message: EXPORT_MESSAGE })
}
}
},
'CallExpression': function (call) {
if (context.getScope().type !== 'module') return
if (
call.parent.type !== 'ExpressionStatement'
&& call.parent.type !== 'VariableDeclarator'
) return
if (call.callee.type !== 'Identifier') return
if (call.callee.name !== 'require') return
if (call.arguments.length !== 1) return
var module = call.arguments[0]
if (module.type !== 'Literal') return
if (typeof module.value !== 'string') return
if (allowRequire(call, options)) return
// keeping it simple: all 1-string-arg `require` calls are reported
context.report({
node: call.callee,
message: IMPORT_MESSAGE,
})
},
}
},
}