简体   繁体   中英

Custom ESLint Import Rule for MaterialUI

I have a project in React, using Material UI, and I am applying one oftheir 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.

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.

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

UPDATE 2022

@kajirikajiri actually made eslint plugin exactly for this!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM