简体   繁体   English

MaterialUI 的自定义 ESLint 导入规则

[英]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.我在 React 中有一个项目,使用 Material UI,我正在应用他们建议的方法之一来减少我的包大小。

Basically, I need to install the babel-plugin-transform-imports package and update the way we import components:基本上,我需要安装babel-plugin-transform-imports package 并更新我们导入组件的方式:

// 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.一切正常,但是,我想防止将来出现“错误”的导入(选项 1)。

Is there a way to customize a ESLint rule that will force the Option 2 import ONLY when importing from the Material UI package?有没有办法自定义 ESLint 规则,在从 Material UI package 导入时强制选项 2 导入?

I was reading about creating a custom ESLint rule, but would prefer to avoid that route.我正在阅读有关创建自定义 ESLint 规则的信息,但希望避免使用该路线。

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. 因此,如果要防止特定于material-ui软件包的默认导入,则您需要创建一个自定义eslint规则,该规则查看导入语句并与material-ui匹配,因为您不想对所有默认导入都出错。

After some research, I found that Material UI created a package with their own custom ESLint rules: 经过研究,我发现Material UI使用自己的自定义ESLint规则创建了一个包:

NPM Package: NPM软件包:

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

GitHub page: GitHub页面:

https://github.com/mui-org/material-ui/tree/master/packages/eslint-plugin-material-ui 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. 他们有一条规则可以解决我的问题( restricted-path-imports ),但是该规则尚未发布。 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://github.com/mui-org/material-ui/issues/15610#issuecomment-512804075

UPDATE 2022 2022 年更新

@kajirikajiri actually made eslint plugin exactly for this! @kajirikajiri实际上正是为此制作了 eslint 插件!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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