EN VI

Reactjs - Enforcing same imported component name as the file it is imported from in react ts modules imports?

2024-03-11 14:00:05
Reactjs - Enforcing same imported component name as the file it is imported from in react ts modules imports?

I have the following code where I export a component , and I want to force the imported name to be the same as the file, this issue with default behavior is that some times you change the file name and the component name yet the olde import name don’t error out, and this would result in confusion when someone want to recognize the complex components what it the best way to disable this behavior ?

MyComponent.tsx:

const MyComponent: React.FC<Props> = ({ /* props */ }) => {
  // component logic
};
export default MyComponent;

AnotherFile.tsx:

import MyComponentX from './MyComponent';

Solution:

You are looking for eslint-plugin-filenames. Considering your project is using typescript, here is how you can use eslint for the same:

Install the dependencies:

npm i eslint --save-dev
npm i eslint-plugin-filenames --save-dev

.eslintrc:

{
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "sourceType": "module",
    "ecmaVersion": 2020
  },
  "overrides": [
    {
      "files": [
        "**/*.tsx"
      ],
      "excludedFiles": [
        "node_modules/**"
      ],
      "rules": {
        "filenames/match-exported": [
          "error",
          "pascal"
        ]
      }
    }
  ],
  "plugins": [
    "filenames"
  ]
}

You can customize the case that you want, such as kebab, snake, pascal etc.

How to use: Just run npx eslint . from your root folder

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login