/
prefer-module.js
333 lines (292 loc) · 8.86 KB
/
prefer-module.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
'use strict';
const {isOpeningParenToken} = require('eslint-utils');
const isShadowed = require('./utils/is-shadowed.js');
const isStaticRequire = require('./utils/is-static-require.js');
const assertToken = require('./utils/assert-token.js');
const {referenceIdentifierSelector} = require('./selectors/index.js');
const {
removeParentheses,
replaceReferenceIdentifier,
removeSpacesAfter,
} = require('./fix/index.js');
const ERROR_USE_STRICT_DIRECTIVE = 'error/use-strict-directive';
const ERROR_GLOBAL_RETURN = 'error/global-return';
const ERROR_IDENTIFIER = 'error/identifier';
const SUGGESTION_USE_STRICT_DIRECTIVE = 'suggestion/use-strict-directive';
const SUGGESTION_DIRNAME = 'suggestion/dirname';
const SUGGESTION_FILENAME = 'suggestion/filename';
const SUGGESTION_IMPORT = 'suggestion/import';
const SUGGESTION_EXPORT = 'suggestion/export';
const messages = {
[ERROR_USE_STRICT_DIRECTIVE]: 'Do not use "use strict" directive.',
[ERROR_GLOBAL_RETURN]: '"return" should be used inside a function.',
[ERROR_IDENTIFIER]: 'Do not use "{{name}}".',
[SUGGESTION_USE_STRICT_DIRECTIVE]: 'Remove "use strict" directive.',
[SUGGESTION_DIRNAME]: 'Replace "__dirname" with `"…(import.meta.url)"`.',
[SUGGESTION_FILENAME]: 'Replace "__filename" with `"…(import.meta.url)"`.',
[SUGGESTION_IMPORT]: 'Switch to `import`.',
[SUGGESTION_EXPORT]: 'Switch to `export`.',
};
const identifierSelector = referenceIdentifierSelector([
'exports',
'require',
'module',
'__filename',
'__dirname',
]);
function fixRequireCall(node, sourceCode) {
if (!isStaticRequire(node.parent) || node.parent.callee !== node) {
return;
}
const requireCall = node.parent;
const {
parent,
callee,
arguments: [source],
} = requireCall;
// `require("foo")`
if (parent.type === 'ExpressionStatement' && parent.parent.type === 'Program') {
return function * (fixer) {
yield fixer.replaceText(callee, 'import');
const openingParenthesisToken = sourceCode.getTokenAfter(
callee,
isOpeningParenToken,
);
yield fixer.replaceText(openingParenthesisToken, ' ');
const closingParenthesisToken = sourceCode.getLastToken(requireCall);
yield fixer.remove(closingParenthesisToken);
for (const node of [callee, requireCall, source]) {
yield * removeParentheses(node, fixer, sourceCode);
}
};
}
// `const foo = require("foo")`
// `const {foo} = require("foo")`
if (
parent.type === 'VariableDeclarator'
&& parent.init === requireCall
&& (
parent.id.type === 'Identifier'
|| (
parent.id.type === 'ObjectPattern'
&& parent.id.properties.every(
({type, key, value, computed}) =>
type === 'Property'
&& !computed
&& value.type === 'Identifier'
&& key.type === 'Identifier',
)
)
)
&& parent.parent.type === 'VariableDeclaration'
&& parent.parent.kind === 'const'
&& parent.parent.declarations.length === 1
&& parent.parent.declarations[0] === parent
&& parent.parent.parent.type === 'Program'
) {
const declarator = parent;
const declaration = declarator.parent;
const {id} = declarator;
return function * (fixer) {
const constToken = sourceCode.getFirstToken(declaration);
assertToken(constToken, {
expected: {type: 'Keyword', value: 'const'},
ruleId: 'prefer-module',
});
yield fixer.replaceText(constToken, 'import');
const equalToken = sourceCode.getTokenAfter(id);
assertToken(equalToken, {
expected: {type: 'Punctuator', value: '='},
ruleId: 'prefer-module',
});
yield removeSpacesAfter(id, sourceCode, fixer);
yield removeSpacesAfter(equalToken, sourceCode, fixer);
yield fixer.replaceText(equalToken, ' from ');
yield fixer.remove(callee);
const openingParenthesisToken = sourceCode.getTokenAfter(
callee,
isOpeningParenToken,
);
yield fixer.remove(openingParenthesisToken);
const closingParenthesisToken = sourceCode.getLastToken(requireCall);
yield fixer.remove(closingParenthesisToken);
for (const node of [callee, requireCall, source]) {
yield * removeParentheses(node, fixer, sourceCode);
}
if (id.type === 'Identifier') {
return;
}
const {properties} = id;
for (const property of properties) {
const {key, shorthand} = property;
if (!shorthand) {
const commaToken = sourceCode.getTokenAfter(key);
assertToken(commaToken, {
expected: {type: 'Punctuator', value: ':'},
ruleId: 'prefer-module',
});
yield removeSpacesAfter(key, sourceCode, fixer);
yield removeSpacesAfter(commaToken, sourceCode, fixer);
yield fixer.replaceText(commaToken, ' as ');
}
}
};
}
}
const isTopLevelAssignment = node =>
node.parent.type === 'AssignmentExpression'
&& node.parent.operator === '='
&& node.parent.left === node
&& node.parent.parent.type === 'ExpressionStatement'
&& node.parent.parent.parent.type === 'Program';
const isNamedExport = node =>
node.parent.type === 'MemberExpression'
&& !node.parent.optional
&& !node.parent.computed
&& node.parent.object === node
&& node.parent.property.type === 'Identifier'
&& isTopLevelAssignment(node.parent)
&& node.parent.parent.right.type === 'Identifier';
const isModuleExports = node =>
node.parent.type === 'MemberExpression'
&& !node.parent.optional
&& !node.parent.computed
&& node.parent.object === node
&& node.parent.property.type === 'Identifier'
&& node.parent.property.name === 'exports';
function fixDefaultExport(node, sourceCode) {
return function * (fixer) {
yield fixer.replaceText(node, 'export default ');
yield removeSpacesAfter(node, sourceCode, fixer);
const equalToken = sourceCode.getTokenAfter(node, token => token.type === 'Punctuator' && token.value === '=');
yield fixer.remove(equalToken);
yield removeSpacesAfter(equalToken, sourceCode, fixer);
for (const currentNode of [node.parent, node]) {
yield * removeParentheses(currentNode, fixer, sourceCode);
}
};
}
function fixNamedExport(node, sourceCode) {
return function * (fixer) {
const assignmentExpression = node.parent.parent;
const exported = node.parent.property.name;
const local = assignmentExpression.right.name;
yield fixer.replaceText(assignmentExpression, `export {${local} as ${exported}}`);
yield * removeParentheses(assignmentExpression, fixer, sourceCode);
};
}
function fixExports(node, sourceCode) {
// `exports = bar`
if (isTopLevelAssignment(node)) {
return fixDefaultExport(node, sourceCode);
}
// `exports.foo = bar`
if (isNamedExport(node)) {
return fixNamedExport(node, sourceCode);
}
}
function fixModuleExports(node, sourceCode) {
if (isModuleExports(node)) {
return fixExports(node.parent, sourceCode);
}
}
function create(context) {
const filename = context.getFilename().toLowerCase();
if (filename.endsWith('.cjs')) {
return {};
}
const sourceCode = context.getSourceCode();
return {
'ExpressionStatement[directive="use strict"]'(node) {
const problem = {node, messageId: ERROR_USE_STRICT_DIRECTIVE};
const fix = function * (fixer) {
yield fixer.remove(node);
yield removeSpacesAfter(node, sourceCode, fixer);
};
if (filename.endsWith('.mjs')) {
problem.fix = fix;
} else {
problem.suggest = [{messageId: SUGGESTION_USE_STRICT_DIRECTIVE, fix}];
}
return problem;
},
'ReturnStatement:not(:function ReturnStatement)'(node) {
return {
node: sourceCode.getFirstToken(node),
messageId: ERROR_GLOBAL_RETURN,
};
},
[identifierSelector](node) {
if (isShadowed(context.getScope(), node)) {
return;
}
const {name} = node;
const problem = {
node,
messageId: ERROR_IDENTIFIER,
data: {name},
};
switch (name) {
case '__filename':
case '__dirname': {
const messageId = node.name === '__dirname' ? SUGGESTION_DIRNAME : SUGGESTION_FILENAME;
const replacement = node.name === '__dirname'
? 'path.dirname(url.fileURLToPath(import.meta.url))'
: 'url.fileURLToPath(import.meta.url)';
problem.suggest = [{
messageId,
fix: fixer => replaceReferenceIdentifier(node, replacement, fixer),
}];
return problem;
}
case 'require': {
const fix = fixRequireCall(node, sourceCode);
if (fix) {
problem.suggest = [{
messageId: SUGGESTION_IMPORT,
fix,
}];
return problem;
}
break;
}
case 'exports': {
const fix = fixExports(node, sourceCode);
if (fix) {
problem.suggest = [{
messageId: SUGGESTION_EXPORT,
fix,
}];
return problem;
}
break;
}
case 'module': {
const fix = fixModuleExports(node, sourceCode);
if (fix) {
problem.suggest = [{
messageId: SUGGESTION_EXPORT,
fix,
}];
return problem;
}
break;
}
default:
}
return problem;
},
};
}
module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
description: 'Prefer JavaScript modules (ESM) over CommonJS.',
},
fixable: 'code',
hasSuggestions: true,
messages,
},
};