问题
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