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

Calling a function within another function

In my code, I have a function that formats the price and retrieves the value needed for refactoring after upgrading our dependencies. I'm struggling with passing the form value to the amountOnBlur function because the blur function in the dependencie ...

What is the most effective way to retrieve a specific type of sibling property in TypeScript?

Consider the code snippet below: const useExample = (options: { Component: React.ComponentType props: React.ComponentProps<typeof options.Component> }) => { return } const Foo = (props: {bar: string; baz: number}) => <></& ...

Encountered an error with Aurelia webpack 4 when trying to load a necessary CSS file during runtime

I encountered a unique issue with webpack and aurelia that I can't seem to figure out. After creating a new webpack configuration based on online resources and official documentation, the compilation goes smoothly without any errors. However, during r ...

Make TypeScript parameter optional if it is not supplied

I am working with an interface that defines scenes and their parameters: export interface IScene<R extends string> { path: R; params?: SceneParams; } The SceneParams interface looks like this: export interface SceneParams { [key: string]: s ...

Delay the Ngrx effect by 2 seconds before initiating the redirect

I have an ngrx effect that involves calling an HTTP method and then waiting for 2 seconds before redirecting to another page. However, the current behavior is that it redirects immediately without waiting. confirmRegistration$ = createEffect(() => { ...

The argument of type 'NextRouter' cannot be assigned to the parameter of type 'Props' in this scenario

In my component, I am initializing a Formik form by calling a function and passing the next/router object. This is how it looks: export default function Reset() { const router = useRouter(); const formik = useFormik(RecoverForm(router)); return ( ...

VScode has identified potential problems with modules that utilize Angular Ivy, however, this should not cause any major issues

Encountering a problem with using Angular in VSCode, where there seems to be no ngModules due to AngularIvy. The error message indicates an issue with 'CommonModule' not being recognized as an NgModule class: [{ "resource": "[...]src/app/com ...

Issues with Rxjs pipe and Angular's Http.get() functionality are causing complications

Working with an Angular 4 Component that interacts with a Service to fetch data is a common scenario. Once the data is retrieved, it often needs to be transformed and filtered before being utilized. The prevailing method for this task is through the use of ...

Tips for calculating the total count of a specific field within a JSON array with TypeScript

I have a JSON array. "user": { "value": [ { "customerNo": "1234" }, { "customerNo": "abcd" }, { "c ...

What is the solution to the strict mode issue in ANGULAR when it comes to declaring a variable without initializing it?

Hi everyone! I'm currently learning Angular and I've encountered an issue when trying to declare a new object type or a simple string variable. An error keeps appearing. this_is_variable:string; recipe : Recipe; The error messages are as follows ...

Can Angular reactive forms be used to validate based on external conditions?

Currently, I am exploring Angular reactive forms validation and facing an issue with implementing Google autocomplete in an input field: <input autocorrect="off" autocapitalize="off" spellcheck="off" type="text" class="input-auto input" formControlName ...

attempting to refine an array of objects using another array within it

I am currently filtering a group of objects in the following manner: [ { "Username":"00d9a7f4-0f0b-448b-91fc-fa5aef314d06", "Attributes":[ { "Name":"custom:organization", "Valu ...

Error: The AppModule is missing a provider for the Function in the RouterModule, causing a NullInjectorError

https://i.stack.imgur.com/uKKKp.png Lately, I delved into the world of Angular and encountered a perplexing issue in my initial project. The problem arises when I attempt to run the application using ng serve.https://i.stack.imgur.com/H0hEL.png ...

PrimeNG's Angular component pTree TreeNode

Is there a way in Angular to retrieve the positions of nodes within a TreeNode hierarchy based on their display order? I have data structured as TreeNode objects, which include children that can branch off further. How can I access these nodes according t ...

Is there documentation available for the gcloud output formats, such as the JSON output for each command?

As I work to script the gcloud tool in a TypeScript-aware JavaScript environment known as SLIME, I am utilizing the --format json feature for formatting. The integration is smooth, but I find myself manual analyzing the JSON output of each command to und ...

What strategies can I use to preserve type narrowing when utilizing the Array.find method?

Within the code snippet below, I am encountering a typescript compilation error specifically in the Array.find method. Despite checking that `context.params.id` is not `undefined`, my type seems to lose its narrowing. I'm puzzled as to why this type ...

having trouble retrieving 200 status code from Angular server response

Objective: I need to make certain changes to the record locally if the server responds with a 200 code. Problem: I am unable to retrieve the response code or access the 'message' attribute. This is the server response I receive from the HTTP ca ...

The module '@angular/http/src/static_response' or its corresponding type declarations could not be located

I'm encountering an issue in my Angular v12 project where I receive the error message Cannot find module '@angular/http/src/static_response' or its corresponding type declarations when I attempt to use the import statement in my code: import ...

Using TypeScript to wrap a class with a Proxy object

I've been working on a function that takes an API interface (I've provided a sample here) and creates a Proxy around it. This allows me to intercept calls to the API's methods, enabling logging, custom error handling, etc. I'm running i ...

Creating interactive features for a TypeScript interface

I was looking to create a dynamic interface with custom properties, like so: data: dataInterface []; this.data = [ { label: { text: 'something', additionalInfo: 'something' } }, { bar: { text: ' ...