skip to Main Content

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.

2

Answers


  1. 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

    Login or Signup to reply.
  2. As an alternative to the approach shown by @vzsoares, you can use the paths option of the no-restricted-imports rule with a simple string value. That will do what you want by default.

    {
      "rules": {
        "no-restricted-imports": [
          "error",
          {
            "paths": [
              {
                "name": "@material-ui/material",
                "message": "Your error message",
              }
            ]
          }
        ]
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search