Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
epidemian
GitHub Repository: epidemian/eslint-plugin-import
Path: blob/main/src/rules/prefer-default-export.js
829 views
1
'use strict';
2
3
import docsUrl from '../docsUrl';
4
5
module.exports = {
6
meta: {
7
type: 'suggestion',
8
docs: {
9
url: docsUrl('prefer-default-export'),
10
},
11
schema: [],
12
},
13
14
create(context) {
15
let specifierExportCount = 0;
16
let hasDefaultExport = false;
17
let hasStarExport = false;
18
let hasTypeExport = false;
19
let namedExportNode = null;
20
21
function captureDeclaration(identifierOrPattern) {
22
if (identifierOrPattern && identifierOrPattern.type === 'ObjectPattern') {
23
// recursively capture
24
identifierOrPattern.properties
25
.forEach(function (property) {
26
captureDeclaration(property.value);
27
});
28
} else if (identifierOrPattern && identifierOrPattern.type === 'ArrayPattern') {
29
identifierOrPattern.elements
30
.forEach(captureDeclaration);
31
} else {
32
// assume it's a single standard identifier
33
specifierExportCount++;
34
}
35
}
36
37
return {
38
'ExportDefaultSpecifier': function () {
39
hasDefaultExport = true;
40
},
41
42
'ExportSpecifier': function (node) {
43
if (node.exported.name === 'default') {
44
hasDefaultExport = true;
45
} else {
46
specifierExportCount++;
47
namedExportNode = node;
48
}
49
},
50
51
'ExportNamedDeclaration': function (node) {
52
// if there are specifiers, node.declaration should be null
53
if (!node.declaration) return;
54
55
const { type } = node.declaration;
56
57
if (
58
type === 'TSTypeAliasDeclaration' ||
59
type === 'TypeAlias' ||
60
type === 'TSInterfaceDeclaration' ||
61
type === 'InterfaceDeclaration'
62
) {
63
specifierExportCount++;
64
hasTypeExport = true;
65
return;
66
}
67
68
if (node.declaration.declarations) {
69
node.declaration.declarations.forEach(function (declaration) {
70
captureDeclaration(declaration.id);
71
});
72
} else {
73
// captures 'export function foo() {}' syntax
74
specifierExportCount++;
75
}
76
77
namedExportNode = node;
78
},
79
80
'ExportDefaultDeclaration': function () {
81
hasDefaultExport = true;
82
},
83
84
'ExportAllDeclaration': function () {
85
hasStarExport = true;
86
},
87
88
'Program:exit': function () {
89
if (specifierExportCount === 1 && !hasDefaultExport && !hasStarExport && !hasTypeExport) {
90
context.report(namedExportNode, 'Prefer default export.');
91
}
92
},
93
};
94
},
95
};
96
97