Path: blob/main/src/rules/prefer-default-export.js
829 views
'use strict';12import docsUrl from '../docsUrl';34module.exports = {5meta: {6type: 'suggestion',7docs: {8url: docsUrl('prefer-default-export'),9},10schema: [],11},1213create(context) {14let specifierExportCount = 0;15let hasDefaultExport = false;16let hasStarExport = false;17let hasTypeExport = false;18let namedExportNode = null;1920function captureDeclaration(identifierOrPattern) {21if (identifierOrPattern && identifierOrPattern.type === 'ObjectPattern') {22// recursively capture23identifierOrPattern.properties24.forEach(function (property) {25captureDeclaration(property.value);26});27} else if (identifierOrPattern && identifierOrPattern.type === 'ArrayPattern') {28identifierOrPattern.elements29.forEach(captureDeclaration);30} else {31// assume it's a single standard identifier32specifierExportCount++;33}34}3536return {37'ExportDefaultSpecifier': function () {38hasDefaultExport = true;39},4041'ExportSpecifier': function (node) {42if (node.exported.name === 'default') {43hasDefaultExport = true;44} else {45specifierExportCount++;46namedExportNode = node;47}48},4950'ExportNamedDeclaration': function (node) {51// if there are specifiers, node.declaration should be null52if (!node.declaration) return;5354const { type } = node.declaration;5556if (57type === 'TSTypeAliasDeclaration' ||58type === 'TypeAlias' ||59type === 'TSInterfaceDeclaration' ||60type === 'InterfaceDeclaration'61) {62specifierExportCount++;63hasTypeExport = true;64return;65}6667if (node.declaration.declarations) {68node.declaration.declarations.forEach(function (declaration) {69captureDeclaration(declaration.id);70});71} else {72// captures 'export function foo() {}' syntax73specifierExportCount++;74}7576namedExportNode = node;77},7879'ExportDefaultDeclaration': function () {80hasDefaultExport = true;81},8283'ExportAllDeclaration': function () {84hasStarExport = true;85},8687'Program:exit': function () {88if (specifierExportCount === 1 && !hasDefaultExport && !hasStarExport && !hasTypeExport) {89context.report(namedExportNode, 'Prefer default export.');90}91},92};93},94};959697