Custom ESLint Import Rule for MaterialUI

与世无争的帅哥 提交于 2021-01-27 21:47:46

问题


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.


回答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.




回答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



来源:https://stackoverflow.com/questions/57495722/custom-eslint-import-rule-for-materialui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!