-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
require-default-import-fallback.cjs
76 lines (70 loc) 路 2.46 KB
/
require-default-import-fallback.cjs
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
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "",
},
fixable: "code",
},
create(ctx) {
return {
ImportDeclaration(node) {
const filename = ctx.getFilename();
const src = node.source.value;
if (
// Not a source file in the monorepo
(!src.includes("/lib/") && !src.startsWith("@babel/")) ||
// This package already always uses the ESM entrypoint.
src === "@babel/helper-plugin-test-runner" ||
// Unclear if we'll convert this or it will stay as JSON.
src.startsWith("@babel/compat-data") ||
// This will not become an ESM file.
src.endsWith(".cjs") ||
// @babel/core automatically unwraps .default from plugins/presets.
/^@babel\/(plugin|preset)-/.test(src) ||
(src.endsWith("./lib/index.js") &&
/babel-(plugin|preset)-/.test(filename))
) {
return;
}
const defaultSpecifier = node.specifiers.find(
spec => spec.type === "ImportDefaultSpecifier",
);
if (!defaultSpecifier) return;
const scope = ctx.getScope();
const { name: local } = defaultSpecifier.local;
const { references } = scope.variables.find(v => v.name === local);
const isRef = node => node.type === "Identifier" && node.name === local;
const isRefDefault = node =>
node.type === "MemberExpression" &&
!node.computed &&
node.property.name === "default" &&
isRef(node.object);
for (const { identifier } of references) {
const base =
identifier.parent.type === "MemberExpression"
? identifier.parent.parent
: identifier.parent;
if (
base.type !== "LogicalExpression" ||
base.operator !== "||" ||
!isRefDefault(base.left) ||
!isRef(base.right)
) {
const expected = `${local}.default || ${local}`;
ctx.report({
node: identifier,
message: `Default imports of source files must be used with an explicit fallback: \`${expected}\``,
fix(fixer) {
const base = isRefDefault(identifier.parent)
? identifier.parent
: identifier;
return fixer.replaceText(base, `(${expected})`);
},
});
}
}
},
};
},
};