Custom ESLint Import Rule for MaterialUI
Asked Answered
F

3

4

I have a project in React, using Material UI, and I am applying one of their suggested methods to reduce my bundle size.

Basically, I need to install the babel-plugin-transform-imports package and update the way we import components:

// Replace this (Option 1):
import Button from "@material-ui/core/Button";
// Whith this (Option 2):
import { Button } from "@material-ui/core";

Everything is working fine, however, I would like to prevent the "wrong" imports (Option 1) in the future.

Is there a way to customize a ESLint rule that will force the Option 2 import ONLY when importing from the Material UI package?

I was reading about creating a custom ESLint rule, but would prefer to avoid that route.

Froward answered 14/8, 2019 at 13:28 Comment(0)
F
2

After some research, I found that Material UI created a package with their own custom ESLint rules:

NPM Package:

https://www.npmjs.com/package/eslint-plugin-material-ui

GitHub page:

https://github.com/mui-org/material-ui/tree/master/packages/eslint-plugin-material-ui

They have a rule to solve my issue (restricted-path-imports), but that is not published yet. When they publish it, that may be the best way to go for me.

Discussion about publishing the rule:

https://github.com/mui-org/material-ui/issues/15610#issuecomment-512804075

Froward answered 14/8, 2019 at 15:54 Comment(0)
K
1

To my knowledge, custom is your only way to go. The only difference between these syntax is importing the default export or a named export. So if you want to prevent default imports specifically for the material-ui packages, you would need to create a custom eslint rule that looked at import statements AND match against material-ui as you don't want to error on all default imports.

Keir answered 14/8, 2019 at 14:56 Comment(1)
Thanks for the answer! I have no experience in creating custom lin rules, so hopefully, someone else may have another idea to avoid this path.Froward
I
1

UPDATE 2022

@kajirikajiri actually made eslint plugin exactly for this!

https://github.com/kajirikajiri/eslint-plugin-mui-path-imports

Inhuman answered 9/9, 2022 at 12:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.