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

Encountering a 404 error when refreshing a page on Firebase hosting with Next.js

I've been exploring the documentation, but I'm stumped as to why refreshing the active page on Firebase hosting results in a 404 error. The website functions flawlessly unless attempting to access a page directly or refreshing the current page (m ...

Explore the Prisma MySQL API search function that allows querying with the ANY

Looking to integrate a search API into my project, but unsure how to handle multiple variables in the query. How can I perform a search for any character using this code snippet? jobs = await prisma.jobOffer.findMany({ where: { ...

A Fresh Approach for Generating Unique UUIDs without Bitwise Operators

To generate UUIDs in TypeScript, I have implemented a method inspired by the solution provided on Stack Overflow. The code effectively converts JavaScript to TypeScript. generateUUID(): string { let date = new Date().getTime(); if (window.performa ...

Struggling to access the "this.array" variable within a TypeScript-powered Angular 4 application

I cannot access the this.array variable in my TypeScript-Angular 4 application. The error is being thrown at this.services.push because this.services is undefined. My code looks like this: export class ServersComponent implements OnInit { //Initializi ...

Learn the process of deploying a Node.js and Express.js Backend to be utilized by a Next.js Frontend through Vercel

Hello everyone, I am looking to deploy my next.js application on Vercel. While there are no issues with that process, I have a separate backend written in Node.js for scalability reasons. I would like to integrate this backend with the Next.js frontend and ...

What is the reason for Jest attempting to resolve all components in my index.ts file?

Having a bit of trouble while using Jest (with Enzyme) to test my Typescript-React project due to an issue with an alias module. The module is being found correctly, but I believe the problem may lie in the structure of one of my files. In my jest.config ...

Cluster multiple data types separately using the Google Maps JavaScript API v3

I am looking to implement MarkerClusterer with multiple markers of various types and cluster them separately based on their type. Specifically, I want to cluster markers of type X only with other markers of type X, and markers of type Y with other markers ...

Various types of generics within an object

Is there a way to achieve different types for the nested K type within a type like MyType? Here's an example: type Config<K> = { value: K; onUpdate: (value: K) => void; } type MyType<F extends string> = { [K in F]: <V>() =& ...

Inputting Dates Manually in the Angular Material Datepicker Field

The datepicker function works well unless I manually type in the date. When I input a date between 01.MM.YYYY and 12.MM.YYYY, the value switches to MM.DD.YYYY. However, if I input 16.09.2021 for example, it remains as DD.MM.YYYY. Is there a way to change ...

Retrieve values from DynamoDB in their original Number or String formats directly

Here is the code I am using to retrieve data from DynamoDB. async fetchData(params: QueryParams) { return await this.docClient.send(new QueryCommand(params)); } const dbObject: QueryParams = { TableName: process.env.TABLE_NAME, KeyCo ...

Learn how to reposition the mat-option easily

I have an angular app with an autocomplete field that I need to adjust the position of. I have consulted the official documentation under the method updatePosition, which states: "Updates the position of the autocomplete suggestion panel to ensure that it ...

Issue with getToken method in NextAuth causing always null response in middleware.ts in NextJS

I'm encountering an issue where I'm unable to retrieve the token data using getToken({req, secret}); it always returns null. I am using Next JS 13.1.1 and next-auth 4.3.4. package.json: { "name": "frontend", "version ...

What is the process for defining the root of a project in ESLint?

I've been working on a project using Next.js and Typescript. My imports look like this: import Component from "/components/Component/Component";, with the root directory being specified as /src. This setup works fine in Next.js, but ESLint k ...

"Users have reported that the file upload preview feature in Angular 6 only works after the

I am currently utilizing Angular 6. In my application, I have a simple input type="file" field that passes data to an image source which displays the image I intend to upload. The issue I am facing is that when I select an image for the first time, nothi ...

Express middleware generator function causing a type error

I recently implemented a function that takes a middleware function, wraps it in a try-catch block, and then returns the modified middleware function. tryCatch.ts import { Request, Response, NextFunction } from "express"; export default function ...

Assigning a value to an Angular class variable within the subscribe method of an HTTP

Understanding the inner workings of this process has been a challenge for me. I've come across numerous articles that touch on this topic, but they all seem to emphasize the asynchronous nature of setting the class variable only when the callback is t ...

Encountering an unexpected redirection issue with Google OAuth2 while using Node.js and Passport

Currently, I am in the process of creating a node.js server utilizing passport middleware to authenticate users through Google's oauth2. The authentication flow can be broken down into the following steps: Users are directed to <server>/aut ...

Angular - Sharing data between components with response value

I am currently in the process of restructuring my project, focusing on establishing communication between unrelated components while also waiting for a return value from a function call. Imagine having component1 with function1() and component2 with funct ...

NextJS component fails to re-render after being updated

I've been diving into the world of useEffect, useState, and rerendering, but I'm struggling to grasp the core issue at hand. While the data update itself is functioning properly, I find myself needing to manually refresh the page in order to see ...

Initiate a timer with intervals of 3 seconds upon reaching a designated section in a React application

useEffect(() => { console.log(window.scrollTo) console.log(textInput.current.offsetTop); }, [textInput,]) click here for more information check out the bottom of this page for a similar countdown feature - any ideas on how to implement it? ...