Navigating to the tsconfig.json file based on the location of the file being linted

In my monorepo, each package currently contains a .eslintrc.cjs file with the following setup:

Package-specific ESLint Configuration

const path = require('path')
const ts = require('typescript')
const OFF = 0
const WARN = 1
const ERROR = 2

const tsConfigPath = path.resolve(__dirname, 'tsconfig.json')

const pathAliases = Object.keys(
  ts.readConfigFile(tsConfigPath, ts.sys.readFile)?.config?.compilerOptions?.paths ?? []
)
  ?.map((key) => key.replace(/[/*@]/g, ''))
  ?.sort()
  ?.join('|')

/**
 * @type {import('eslint').Linter.Config}
 * @see https://eslint.org/docs/user-guide/configuring
 **/
module.exports = {
  rules: {
    'simple-import-sort/imports': [
      ERROR,
      {
        groups: [
          ['^@?\\w'],
          pathAliases.length ? [`^@?(${pathAliases})(/.*|$)`] : [],
          ['^\\u0000'],
          ['^\\.\\.(?!/?$)', '^\\.\\./?$'],
          ['^\\./(?=.*/)(?!/?$)', '^\\.(?!/?$)', '^\\./?$'],
        ],
      },
    ],
  },
}

Root ESLint Configuration

const OFF = 0
const WARN = 1
const ERROR = 2

/**
 * @type {import('eslint').Linter.Config}
 * @see https://eslint.org/docs/user-guide/configuring
 **/
module.exports = {
  root: true,
  env: {
    browser: true,
    node: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:jest-formatting/recommended',
    'plugin:sonarjs/recommended',
    'plugin:import/typescript',
    'prettier',
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module',
    project: [
      './tsconfig.browser.base.json',
      './tsconfig.browser.base.json',
      './packages/service/*/tsconfig.json',
      './packages/utility/*/tsconfig.json',
      './packages/middleware/*/tsconfig.json',
    ],
    tsconfigRootDir: __dirname,
    ecmaFeatures: {
      impliedStrict: true,
    },
  },
  plugins: [],
  rules: {},
}

This setup retrieves the pathAliases from the TSConfig and integrates it into the simple-import-sort ESLint rule. I am exploring ways to consolidate this configuration into the root eslint config so that each linted file can access the relative tsconfig paths property efficiently.

Answer №1

ESLint configurations do not receive specific details about the file being linted and there is no mechanism to include this information in the configuration file.

This limitation exists because ESLint can be accessed through various methods, such as the built-in CLI or IDE extensions. However, ESLint also offers an API that allows anyone to run ESLint on text input, with or without specifying a filename.

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

What is the proper method for utilizing a conditional header in an rtk query?

How can I implement conditional header authentication using rtk query? I need to pass headers for all requests except refresh token, where headers should be empty. Is it possible to achieve this by setting a condition or using two separate fetchBaseQuery ...

When setting a value that has been explicitly casted, the original literal type remains intact for the new property or variable

After defining the constant MODE with specific values, I noticed something interesting: const MODE = { NONE: 0 as 0, COMPLETED: 1 as 1, DELETED: 2 as 2 } as const // In a CreateReactApp project, enums aren't available It became appar ...

Extracting PNG file from response (bypassing standard JSON extraction)

Despite my efforts to find a solution, I am still unable to resolve this specific issue: I have implemented an Angular request (localhost:4200) to an API on Spring (localhost:8080). The HttpService successfully handles the requests, except when it comes to ...

Organize routes into distinct modules in Angular 6

Currently grappling with routing in my Angular 6 application. Wondering if the structure I have in mind is feasible. Here's what it looks like: The App module contains the main routing with a parent route defining the layout: const routes: Routes = ...

Angular 14 is throwing an error due to an indent issue - the expected indentation is 2 spaces but 4 spaces were found

Currently using "eslint": "^8.23.0" with angular 14. Everything was functioning properly with "eslint": "^8.22.0", but after updating to 8.23.0, I encountered the following error: This is my eslint configuration: ...

Tips for transforming an Observable stream into an Observable Array

My goal is to fetch a list of dogs from a database and return it as an Observable<Dog[]>. However, whenever I attempt to convert the incoming stream to an array by using toArray() or any other method, no data is returned when calling the retrieveDo ...

DxDataGrid: Implementing a comprehensive validation system for multiple edit fields

I'm currently working with a DxDataGrid within an Angular Application. Within this particular application, I have the need to input four dates. I've implemented validation rules that work well for each individual field. However, my challenge aris ...

Tips for changing a "raw" DOM Event into a React SyntheticEvent

Currently, I am working with two separate libraries. The first library emits "raw" DOM events (lib.dom.d.ts), while the other library consumes React.SyntheticEvents. I am seeking advice on the most efficient method to transform the raw event into a Synthe ...

Angular 2's ng-required directive is used to specify that

I have created a model-driven form in Angular 2, and I need one of the input fields to only show up if a specific checkbox is unchecked. I was able to achieve this using *ngIf directive. Now, my question is how can I make that input field required only whe ...

how can I retrieve only the child route in next js?

Need help with this title. This is my Next JS project and I am working on a custom breadcrumb component. Everything seems to be going well so far, but I am facing an issue with the /people page followed by the /people/roles page. I want to extract only the ...

Enhance the aesthetic appeal of the imported React component with added style

I need assistance with applying different styles to an imported 'notification' component within my header component. The notification component has its own CSS style, but I want to display it in the header component with unique styling. How can I ...

Troubleshooting an angular problem with setting up a dynamic slideshow

I am currently working on building a slideshow using plain HTML, CSS, and JavaScript. I referred to the following example for guidance: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_slideshow_auto However, despite implementing the code prov ...

Unable to locate any NativeScript modules for tns-core-module/ui

I'm working on a {N}-Application and facing an issue with importing Images from the tns-core-modules/ui/image module. Unfortunately, it seems that the target cannot be found within the tns-core-module. This is my code snippet: import * as ImageModul ...

Can data from an Angular app be accessed by an external JavaScript code within the same project?

I've been thinking about a theoretical scenario that luckily I haven't encountered yet. Imagine I have an Angular Project compiled in My PROJECT FOLDER. <br/> Inside this PROJECT FOLDER, there's another JAVASCRIPT FILE external to ...

Does anyone have experience using the useRef hook in React?

Can someone help me with this recurring issue: "Property 'value' does not exist on type 'never'" interface InputProps { name: string; icon?: ReactElement; placeholder?: string; } const Input = ({ name, icon: Icon, ...rest }: Inpu ...

I am experiencing an issue with applying responsiveFontSize() to the new variants in Material UI Typography

I am looking to enhance the subtitles in MUI Typography by adding new variants using Typescript, as outlined in the documentation here. I have defined these new variants in a file named global.d.ts, alongside other customizations: // global.d.ts import * a ...

Error: The variable _ is undefined when trying to use the .map() function on an array

While working on my project, I encountered a "ReferenceError: _ is not defined" when using the .map function in this code snippet: arr.map(async (elem) => { ... }); I couldn't find any explicit mention of "_" in my code. The error trace pointed me ...

Practical strategy for developing and launching a TypeScript/Node.js application

I'm currently developing a node.js app using Typescript, which requires compilation to JS before running. As someone with a background in java/jvm, I'm hesitant about the deployment process where code is pushed to git, built/compiled on the serve ...

Dealing with Errors in Node.js Using Typescript and Express

As I embark on my journey with Node and Typescript, a question has cropped up in my mind. There are two key files in my project: server.ts import express = require('express'); import IConfiguration from "../config/config"; export default clas ...

Maintaining scroll position in React Router v6

My website's homepage displays a user's feed. When a user clicks on one of the feed cards, they are taken to a different URL. However, when the user returns to the homepage, it automatically scrolls to the top. I am looking for a way to preserve ...