My goal is to intentionally trigger an eslint error when importing a file from index.ts

Is there a way to enforce importing components from index.ts within the src/components directory using eslint rules or plugins?


// index.ts (src/components/Forms)
export { Input } from './Input';
export { CheckBox } from './CheckBox';
export { Button } from './Button';
pages/home.tsx

import { Input,CheckBox,Button } from  "src/components/Forms" // success
import { Button } from "src/components/Forms/Button" //error
import { Input } from "src/components/Forms/Input" //error

The current eslintrc.js configuration is as follows:
Added @typescript-eslint/no-restricted-imports.

module.exports = {
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 2020,
    sourceType: 'module',
  },
  extends: [
    'plugin:@typescript-eslint/recommended',
    'plugin:react/recommended',
    'plugin:react-hooks/recommended',
    'plugin:jsx-a11y/recommended',
    'prettier',
    'plugin:prettier/recommended',
  ],
  settings: {
    react: {
      version: 'detect',
    },
  },
  plugins: ['import', 'no-relative-import-paths'],
  rules: {
    'react/prop-types': 'off',
    'react/react-in-jsx-scope': 'off',
    'jsx-a11y/anchor-is-valid': 'off',
    'jsx-a11y/no-onchange': 'off',
    'jsx-a11y/no-static-element-interactions': 'off',
    'jsx-a11y/click-events-have-key-events': 'off',
    '@typescript-eslint/ban-ts-comment': 'warn',
    '@typescript-eslint/no-unused-vars': 'error',
    'no-unused-vars': 'off',
    'no-relative-import-paths/no-relative-import-paths': [
      'error',
      { allowSameFolder: false, rootDir: './src' },
    ],
    'prettier/prettier': 'warn',
    '@typescript-eslint/explicit-module-boundary-types': 'off',
    '@typescript-eslint/explicit-function-return-type': 'off',
    'react/display-name': 'off',
    '@typescript-eslint/no-restricted-imports"': [
      'error',
      {
        patterns: [
          {
            group: [
              'src/components/common/*/*',
              '!src/components/common/*/index',
            ],
            message: 'import from .../index.js instead',
          },
        ],
      },
    ],
  },
};

//src/pages/index.page.tsx  
import { Select, Button } from 'components/common/Forms';
import { CheckBox } from 'components/common/Forms/CheckBox';

Answer №1

Perhaps something along these lines:

{
  "rules": {
    "@typescript-eslint/no-restricted-imports": [
      "error",
      {
        "patterns": [
          {
            "group": [
              "src/components/*/*",
              "!src/components/*/index.js"
            ],
            "message": "please import from .../index.js instead"
          }
        ]
      }
    ]
  }
}
// index.tsx

import { Dropdown } from  "src/components/Nav/index.js" // success
import { Navbar } from "src/components/Nav/Navbar" // error
import { Menu } from "src/components/Nav/Menu" // error

Resources:

Answer №2

After some trial and error, I managed to make it function as intended:

'@typescript-eslint/no-restricted-imports': [
      'error',
      {
        paths: [
          {
            name: '.',
            message: '<custom message>',
          },
          {
            name: '..',
            message: '<custom message>',
          },
        ],
      },

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

How to Access Static Method from Non-Static Method in TypeScript

Within my hierarchy, there is some static content present in all levels (for example, the _image). It would be ideal to access the corresponding _image without repeating code: Here's what I envision: class Actor { static _image; // Needs to be s ...

"Learn the trick of converting a stream into an array seamlessly with RxJs.toArray function without the need to finish the

In order to allow users to filter data by passing IDs, I have created a subject that can send an array of GUIDs: selectedVacancies: Subject<string[]> = new Subject(); selectedVacancies.next(['a00652cd-c11e-465f-ac09-aa4d3ab056c9', ...

Step-by-step guide to setting up a TypeScript project on Ubuntu 15 using the

As a newcomer to UBUNTU, I have recently ventured into learning AngularJS2. However, when attempting to install typescript using the command: NPM install -g typescript I encountered the following error message: view image description here ...

The process of implementing ngOninit with asynchronous data involves handling data that may take

Within the ngOnInit method, I am calling a service method and assigning the return value to a member variable. However, when trying to access this variable later in the ngOnInit again, it seems that due to synchronization issues, the value has not been ass ...

The validation process in reactive forms is experiencing some issues with efficiency

Trying to debug an issue with my reactive forms - the repeatPassword field doesn't update as expected. When entering information in the "password" field, then the "repeatPassword" field, and back to "password", the second entry is not flagged as inval ...

Applying Conditional Rendering in React using API Data Retrieval

I'm facing an issue: I need to display only the "nameProcess" and "id" in the table that have the attribute "error = true" in the json file. I've fetched the data but now I'm struggling to implement the condition inside my function. Can an ...

How can I uniquely combine a code with an existing CSS class and make modifications to it?

I am using ngx-skeleton-loader and I would like to change the color, but I am facing some difficulties. Here is an image that illustrates the issue. When looking at the developer tools, you can see the styles action in the styles action bar. .loader ...

Transfer my testing utilities from React Router version 5 to version 6

I am currently transitioning my project to React V6 router and encountering an issue with my test utility function. Every time I run the test, all my expectations fail because jest cannot locate the object. Has anyone faced this error during a similar migr ...

Webpages appear distorted. Nextjs version 13 deployed on Digital Ocean

When I directly access the pages of my next.js website, they appear as strings of code without any errors in the Console (Chrome or Safari, with no cache). The functionality may or may not work normally when navigating from the homepage. This is a Next.js ...

Difficulty in Rendering Data with Next Js

I'm currently working on integrating data from an API by following the steps outlined in the Next documentation. Unfortunately, I am experiencing difficulties as the data is not rendering. This project marks my first venture into React, so I may be ov ...

Whenever a socket event occurs, the state of Nextjs is automatically reset

I attempted to implement chat functionality into my Nextjs app. Despite following the documentation, the chat log gets reset every time a socket event occurs. Below is the code snippet: import { useState, useEffect } from 'react' import io from & ...

What is the best way to switch to a different screen in a React Native application?

I've recently dived into the world of React Native and embarked on a new project. The initial screen that greets users upon launching the app is the "welcome screen," complete with a prominent 'continue' button. Ideally, clicking this button ...

Angular validation for password and confirmation password fields

I have been working on implementing password and confirm password validation within an angular project. I recently came across a helpful answer on this thread Confirm password validation in Angular 6 that I tried to follow. Unfortunately, I am encountering ...

Next.js fails to load TailwindCSS

I am in the process of developing an app using tailwindcss and next.js First, I started creating the nextjs app, then I executed these commands: npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -p Following that, I made adjustments t ...

Tips for avoiding double reservations and creating time slots with nextjs and prisma

Welcome to my NextJS app booking system. As a beginner, I'm exploring how to create a website for simple bookings and have successfully connected it to Netlify. Currently, I can gather booking details such as time and name using Netlify forms. Howeve ...

Developing a bespoke React Typescript button with a custom design and implementing an onClick event function

Currently, I am in the process of developing a custom button component for a React Typescript project utilizing React Hooks and Styled components. // Button.tsx import React, { MouseEvent } from "react"; import styled from "styled-components"; export int ...

Is there a way to use WithStyles<typeof styles> within Material UI?

import { WithStyles, createStyles } from '@material-ui/core'; const styles = (theme: Theme) => createStyles({ root: { /* ... */ }, paper: { /* ... */ }, button: { /* ... */ }, }); interface Props extends WithStyles<typeof styles> ...

Setting up Typescript with React 17 and Tailwind CSS version 2.0

I'm struggling to set up TailwindCSS 2.0 with the create-react-app --template typescript configuration and encountering errors. Even after following the instructions on the official TailwindCSS website for React at https://tailwindcss.com/docs/guides/ ...

What could be causing the sluggish hot reloading in my Next.js 14 application that utilizes TailwindCSS, Shadcn, and React Icons?

I've been struggling with slow hot reloading times in my Next.js 14 project that incorporates TailwindCSS, Shadcn, and React Icons. Below is a comprehensive list of all the packages I have installed: radix-ui/<a href="/cdn-cgi/l/email-protection" c ...