javascriptreactjsnext.jsmaterial-uieslint

ESLint custom rule to restrict Material UI imports


I'm working in a project that's in Nextjs 14 with Material UI 5 components for styling. I want to know if there's a ESLint custom rule to restrict the way of importing the components, probably with no-restricted-imports.

// This should trigger an error
import { Box } from "@material-ui/material";
// This should be allowed
import Box from "@material-ui/material/Button";

Is there a custom ESLint rule that would satisfy my needs instead that I can easily put into the rules section? Plugins that are not deprecated are also welcome.

I already tried various configs with no-restricted-imports but couldn't hack it. Maybe someone with more experience on ESLint can help me.


Solution

  • Just made it work using some propper regex:

    "no-restricted-imports": ["error", {
        "patterns": [{
          "regex": "@material-ui\/material$",
          "message": "No root mui import"
    }]
    

    @material-ui\/material$ escape the forward slash and mark end of string using dollar sign $

    playground

    Edit: if you also want to block when it might have a slash in the end like: import { Box } from "@material-ui/material/" then use this expression @material-ui\/material\/{0,1}$