[d565449] | 1 | /**
|
---|
| 2 | * @fileoverview Prevent multiple component definition per file
|
---|
| 3 | * @author Yannick Croissant
|
---|
| 4 | */
|
---|
| 5 |
|
---|
| 6 | 'use strict';
|
---|
| 7 |
|
---|
| 8 | const values = require('object.values');
|
---|
| 9 |
|
---|
| 10 | const Components = require('../util/Components');
|
---|
| 11 | const docsUrl = require('../util/docsUrl');
|
---|
| 12 | const report = require('../util/report');
|
---|
| 13 |
|
---|
| 14 | // ------------------------------------------------------------------------------
|
---|
| 15 | // Rule Definition
|
---|
| 16 | // ------------------------------------------------------------------------------
|
---|
| 17 |
|
---|
| 18 | const messages = {
|
---|
| 19 | onlyOneComponent: 'Declare only one React component per file',
|
---|
| 20 | };
|
---|
| 21 |
|
---|
| 22 | /** @type {import('eslint').Rule.RuleModule} */
|
---|
| 23 | module.exports = {
|
---|
| 24 | meta: {
|
---|
| 25 | docs: {
|
---|
| 26 | description: 'Disallow multiple component definition per file',
|
---|
| 27 | category: 'Stylistic Issues',
|
---|
| 28 | recommended: false,
|
---|
| 29 | url: docsUrl('no-multi-comp'),
|
---|
| 30 | },
|
---|
| 31 |
|
---|
| 32 | messages,
|
---|
| 33 |
|
---|
| 34 | schema: [{
|
---|
| 35 | type: 'object',
|
---|
| 36 | properties: {
|
---|
| 37 | ignoreStateless: {
|
---|
| 38 | default: false,
|
---|
| 39 | type: 'boolean',
|
---|
| 40 | },
|
---|
| 41 | },
|
---|
| 42 | additionalProperties: false,
|
---|
| 43 | }],
|
---|
| 44 | },
|
---|
| 45 |
|
---|
| 46 | create: Components.detect((context, components, utils) => {
|
---|
| 47 | const configuration = context.options[0] || {};
|
---|
| 48 | const ignoreStateless = configuration.ignoreStateless || false;
|
---|
| 49 |
|
---|
| 50 | /**
|
---|
| 51 | * Checks if the component is ignored
|
---|
| 52 | * @param {Object} component The component being checked.
|
---|
| 53 | * @returns {Boolean} True if the component is ignored, false if not.
|
---|
| 54 | */
|
---|
| 55 | function isIgnored(component) {
|
---|
| 56 | return (
|
---|
| 57 | ignoreStateless && (
|
---|
| 58 | /Function/.test(component.node.type)
|
---|
| 59 | || utils.isPragmaComponentWrapper(component.node)
|
---|
| 60 | )
|
---|
| 61 | );
|
---|
| 62 | }
|
---|
| 63 |
|
---|
| 64 | return {
|
---|
| 65 | 'Program:exit'() {
|
---|
| 66 | if (components.length() <= 1) {
|
---|
| 67 | return;
|
---|
| 68 | }
|
---|
| 69 |
|
---|
| 70 | values(components.list())
|
---|
| 71 | .filter((component) => !isIgnored(component))
|
---|
| 72 | .slice(1)
|
---|
| 73 | .forEach((component) => {
|
---|
| 74 | report(context, messages.onlyOneComponent, 'onlyOneComponent', {
|
---|
| 75 | node: component.node,
|
---|
| 76 | });
|
---|
| 77 | });
|
---|
| 78 | },
|
---|
| 79 | };
|
---|
| 80 | }),
|
---|
| 81 | };
|
---|