Does Eslint's no-restricted-imports rule only limit imports from the package's root directory?

For example, I'm looking to limit the usage of importing react-use, while still permitting react-use/lib/usePrevious. I attempted this:

  rules: {
    'no-restricted-imports': [2, { patterns: [
      'react-use',
    ] }],
  },

As well as:

  rules: {
    'no-restricted-imports': [2, { patterns: [
      'react-use',
      '!react-use/*',
    ] }],
  },

But in both scenarios, I encounter an error with:

import usePrevious from 'react-use/lib/usePrevious';

I specifically want the error to trigger only for:

import something from 'react-use';

Answer №1

I was looking to achieve a similar result using lodash.

Regarding Treeshaking, I aimed to limit

import {get} from 'lodash';

but allow

import get from 'lodash/get';

This is my eslint configuration for achieving this:

'no-restricted-imports': [
      'error',
      {
        paths: [
          {
            name: 'lodash',
            message:
              "Please use `import [package] from 'lodash/[package]'` instead."
          }
        ],
        patterns: ['!lodash/*']
      }
    ]

You could implement a similar approach for your own package as well.

Answer №2

The issue lies within the ignore library utilized by ESLint for pattern checking. This library was designed to offer a more streamlined and basic alternative to existing file ignore methods.

More specifically, the challenge arises from the assumption made by this ignore system regarding the structure of your files. It operates under the belief that when you limit react-use while simultaneously ignoring !react-use/*, it interprets react-use as a directory. However, in a module import setup, react-use can pertain to a file (such as its index.js) while also housing subdirectories like react-use/lib, thus functioning as both a file and a directory.

This creates a scenario where excluding the module's base while limiting a subdirectory becomes unfeasible.

Answer №3

If you are interested in creating a rule to optimize bundle size while using the @mui/icons-material package,

    "no-restricted-imports": [
      "error",
      {
        paths: [
          {
            name: "@mui/icons-material",
            message: "Please use `import SomeIconName from '@mui/icons-material/SomeIconName'` instead, to reduce compilation bundle size.",
          },
        ],
        patterns: ["@mui/*/*/*", "!@mui/icons-material/*"],
      },
    ],

Answer №4

If you're struggling to find a solution, feel free to refer to the ESLint documentation.

Including the "default" string in the importNames array will prevent importing the default export.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Include an item in a Vuetify model's array of objects

Currently, I am attempting to store the value of a dynamically loaded radio button into an array of objects. These radio buttons serve as options for a set of questions within a form, and my desired output is as follows: [{"question1":{ " ...

How can we ensure that an enum is accessible throughout the entire meanjs stack?

Currently, I am exploring the meanjs technology stack and facing a challenge in creating a centralized enum array that can be accessed throughout the project, from MongoDB to Angular. Can anyone suggest a smart solution for accomplishing this task? ...

Is it possible to pass a random variable into an included template in Jade?

In my jade template called 'main page', I have a reusable template named 'product template'. The 'product template' is designed to display dynamic data and needs to be flexible enough to be used in multiple pages without being ...

Changing tabs will redirect the url

Having an issue with ASP AjaxControlToolkit tabs. I want the URL to change based on the tab selected by the user. Check out the code snippet below: <asp:TabContainer ID="TabContainer1" runat="server" Width="100%" Height="100%"> <asp:TabPanel ...

Displaying a JavaScript array containing multiple arrays

I have a collection of arrays, each containing a set of list items, which I am displaying using console.log(jobsList);. The output looks like this: The variable jobsList is generated by adding arrays created inside a for loop like this: for (var i=0; i ...

React native and redux: Updating state with setState is not possible during an ongoing state transition

Currently in the process of developing an app utilizing React Native and redux, alongside Express js for handling Ajax requests. Encountering an issue where the data from my Ajax request fails to load, accompanied by the following warning: Warning: set ...

IIS Alert: Missing Images, CSS, and Scripts!

When I tried to publish my website using IIS, I encountered the error message Cannot read configuration file due to insufficient permissions. After attempting to add permissions for IIS_USRS and realizing that this user does not exist on my computer runnin ...

The python-pyinstrument is in need of a javascript dependency that seems to

As I attempt to profile my Python program using pyinstrument, I encounter an error when trying to view the profile in HTML format. Traceback (most recent call last): File "/home/ananda/projects/product_pred/025200812_cpall_ai_ordering_model_v2/.venv ...

AngularJS: Double the power of Ajax. Can you assist me?

ajax was successful twice. Take a look. https://i.sstatic.net/QLdpT.png https://i.sstatic.net/zAbXW.png ...

Control the playback of individual HTML5 audio elements using jQuery for seamless user experience

How can I modify the code to ensure that only one HTML5 audio element plays at a time? Currently, all tracks are able to play simultaneously. I am using jQuery for play and pause functionalities. If one track is playing and another is clicked on, how can ...

Using Regular Expressions to access a deeply nested object

Within my JS objects, there is a common grandchild property called 'products'. For example: ecommerce.add.products, ecommerce.remove.products, ecommerce.detail.products, ecommerce.checkout.products, ecommerce.purchase.products I am attempting t ...

Troubleshooting Angular 2 with TypeScript: Issue with view not refreshing after variable is updated in response handler

I encountered a problem in my Angular 2 project using TypeScript that I could use some help with. I am making a request to an API and receiving a token successfully. In my response handler, I am checking for errors and displaying them to the user. Oddly en ...

Utilize CSS with dynamically created elements

I am currently figuring out how to use my .each() function with a $(document).ready and a click event. Here's what I have so far: $(document).ready(function(){ $(".help-inline").each(function() { $(this).css('display', 'none&apos ...

`Javascript often returns NaN for basic calculations`

Hello, I am currently developing a basic calculator for a game but I have encountered an issue. Despite having just started learning this programming language and reading all available tutorials, I am now in the process of writing code to gain more experie ...

Is your Angular 2 routing failing to work properly after a page refresh or reload when using gulp?

I've recently started learning Angular 2, and I encountered an issue with routing. During the development phase, I ran my application using npm start. However, after migrating to gulp.js, when I run the application by typing gulp, everything works fin ...

Unable to retrieve button value with material-ui package

My task requires me to retrieve the value of a button, as it contains an ID essential for further steps. Initially, I used a standard button with Bootstrap styling and everything functioned correctly. <button value={row.vacationRequestID} c ...

Decoding the Language of HTTP Status Codes

Let's imagine a scenario where I create a file called api.js: const {somefunction} = require('../controllers/some-controller'); app.get('/data/', somefunction); In my some-controller.js: exports.somefunction = async (req, res,next ...

React - Can you explain the purpose of the callback function in the forceUpdate method?

The React documentation mentions that the forceUpdate method includes a parameter called callback. Does this function in any way resemble the second parameter found in setState, which is executed after setting state? Or does it serve a different purpose? ...

What is the simplest method for preserving the Redux state?

What is the most efficient method to maintain state in Redux even after a website refresh? I would prefer not to rely on redux-persist if there are alternative options available. ...

A guide on utilizing multer-sftp for downloading files

I've been working on this code, but after searching online I still haven't found a way to download a file from the remote server. I can successfully upload files to the server, but downloading them is posing a challenge. var storage = sftpStorag ...