When tests/** are not included in the tsconfig, the TS language features in Vscode become inaccessible

I am looking to configure my TypeScript tests in such a way that they receive linting, code completion, and VSCode intellisense (TypeScript language features) when the test folder is placed next to the src folder. However, I want to ensure that my tests do not transpile when building my TypeScript project.

The structure of my TypeScript node project looks like this:

.    
├── server
│   │ 
│   │    
│   ├── src
│   │   │
│   │   └── app.ts
│   ├── test
│   │   │
│   │   └── app.test.ts
│   ├── node_modules/
│   ├── package-lock.json
│   ├── package.json
│   ├── tslint.json
│   └── tsconfig.json
├── front_end/
└── README.md

Here's an excerpt from my tsconfig:

{
  "compilerOptions": {
    "baseUrl": ".",
    "module": "commonjs",
    "moduleResolution": "node",
    "outDir": "dist",
    "sourceMap": true,
    "strict": true,
    "target": "ESNext",
    "paths": {
      "*": ["node_modules/*"]
    }
  },
  "include": ["src/**/*"]
}

When I access my test files in VSCode, the language feature does not recognize types and packages installed in node_modules. Interestingly, if I open VSCode only in the server folder (which is not the root based on my folder structure), the language features work properly 🧐.

My tests utilize ts-jest for execution, hence eliminating the need for tsc. Would it be recommended to extend a separate tsconfig.json specifically for tests 🤔?

Should I try tweaking some settings or consider submitting a bug report to https://github.com/microsoft/vscode/issues/new/choose.

Answer №1

There is an issue with Vscode when using a single root tsconfig file. If you have a test folder adjacent to the src folder, it will use the tsconfig (added in this specific pull request) but it may not work properly if the folder you open is one directory above it, such as having a server and client folder setup. You can follow the progress of the solution for this problem in this GitHub issue.

Furthermore, if you are looking to switch from tslint to eslint, you will need to add a tsconfig file to the test folder in order to exclude it from the main tsconfig. You can find detailed instructions on how to set up eslint with multiple tsconfig files in the provided link.

An easy workaround for these issues is to create two additional tsconfig files - one for the linter (tsconfig.eslint.json) and one specifically for tests inside the test folder (test/tsconfig.json). The content of the test tsconfig file should include the following:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "noEmit": true
  },
  "include": ["./**/*"]
}

Although this solution may not be very elegant, at the moment it seems to be the best available option.

Answer №2

Unfortunately, I am currently without my computer to verify this, but it seems that you simply need to insert the following code into your ts json file.

"exclude": [
        "node_modules",
        "**/*.test.ts"
    ]

Breakdown: Exclude ** all directories / * all TypeScript files containing .test in their names.

If you are not utilizing node then you may exclude the node_modules section. However, I have included it in my response for those who do use node and may copy the exclusion. By default, node_modules is already excluded, but additional modifiers can override that.

Best of luck with your implementation.

I hope this solution aligns with what you are seeking.

Answer №3

A useful tip is to extend your tsconfig for a common, production, and development setup. Here's how we do it:

tsconfig.common.json - holds shared settings for both development and production environments.

tsconfig.json - the development version with tests included:

{
    "extends": "./tsconfig.common",
    "exclude": ["bin", "node_modules"]
}

tsconfig.prod.json - the production version without tests:

{
    "extends": "./tsconfig.common",
    "exclude": ["bin", "node_modules", "tests", "**/*.spec.ts"]
}

In our webpack.config, we follow a similar structure:

webpack.common.js - contains shared configurations for both environments

webpack.dev.js - utilizes the development tsconfig:

rules: [
        {
            test: /\.ts$/,
            exclude: [/bin/, /node_modules/],
            include: /ClientApp/,
            loader: 'ts-loader',
            options: {
                appendTsSuffixTo: [/\.vue$/],
                configFile: 'tsconfig.json'
            }
        }
    ]

webpack.prod.js - uses the production tsconfig:

rules: [
        {
            test: /\.ts$/,
            exclude: [/bin/, /node_modules/],
            include: /ClientApp/,
            loader: 'ts-loader',
            options: {
                appendTsSuffixTo: [/\.vue$/],
                configFile: 'tsconfig.prod.json'
            }
        }
    ]

Lastly, ensure the package.json file includes the following scripts:

scripts: {
    "dev": "webpack --config webpack.dev.js",
    "build": "webpack --config webpack.prod.js",
}

This approach should streamline your configuration process. Good luck!

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

Prevent the Icon in Material UI from simultaneously changing

I'm working on a table where clicking one icon changes all icons in the list to a different icon. However, I want to prevent them from changing simultaneously. Any suggestions on how to tackle this issue? Code: import React from 'react'; im ...

What is the correct method for storing a response in an array variable in Angular?

I am looking to save the response data from an API call in a variable and display it in the component.html file. Component.ts file : public coinsHistory = []; this.service.getCoinsHistory().subscribe( (response) => { this.handleCoinsRespon ...

Exploring through objects extensively and expanding all their values within Angular

I am in need of searching for a specific value within an object graph. Once this value is found, I want to set the 'expanded' property to true on that particular object, as well as on all containing objects up the object graph. For example, give ...

An easy method to define argument types for every function type in TypeScript

How can I assign argument types to each function type in TypeScript? Each function has a parameter associated with it. [Example] type F1 = (arg: number) => void; type F2 = (arg: string) => void; const caller = (f: F1 | F2) => (n: number | strin ...

Guide on how to create a custom response using class-validator in NestJS

Is it feasible to customize the error response generated by class-validator in NestJs? The default error message structure in NestJS looks like this: { "statusCode": 400, "error": "Bad Request", "message": [ { "target": {} ...

Retrieving information from a JSON object in Angular using a specific key

After receiving JSON data from the server, I currently have a variable public checkId: any = 54 How can I extract the data corresponding to ID = 54 from the provided JSON below? I am specifically looking to extract the values associated with KEY 54 " ...

Combining Rollup, Typescript, and converting images to base64 during the loading process

Having trouble preloading an image with Rollup. None of the solutions that should work seem to be effective, and I can't figure out why. Has anyone successfully managed to make this work? Here is my configuration in rollup.config.js: import image fr ...

Can ngFor be utilized within select elements in Angular?

I'm facing an interesting challenge where I need to display multiple select tags with multiple options each, resulting in a data structure that consists of an array of arrays of objects. <div class="form-group row" *ngIf="myData"> <selec ...

What is the best way to retrieve a specific field from the observable data stream?

When working with observables, I often find myself using them like this: ... const id = 1337; this.service.getThing(id).subscribe( suc => doSomething(suc.name), err = doSomethingElse() ); Lately, I've been utilizing the async pipe more freque ...

Utilizing images in a compiler run with the option of `allowJS:true` is key

Looking to develop a React Native library using JavaScript instead of typescript, but want to leverage TSC for its ability to generate type declarations from jsdoc comments. However, encountering an issue where local images are not included when the ts com ...

Validating patterns in Angular without using a form

Seeking guidance on validating user input in Angular6 PrimeNG pInputText for a specific URL pattern, such as , possibly triggered on blur event. This particular field used to be part of a form but has since been relocated to a more complex 6-part form int ...

Attempting to invoke a TypeScript firebase function

I'm currently working on incorporating Firebase functions in my index.ts file: import * as functions from "firebase-functions"; export const helloWorld = functions.https.onRequest((request, response) => { functions.logger.info(" ...

Is there a way to make Firebase Cloud Functions utilize ESLint?

Is there a specific command to activate ESLint for my cloud functions? Just to provide some context, I executed firebase init and completed the setup process, but it ended up using ESLint instead of TSLint which was unexpected. After that, I ran firebase ...

Problem with organizing data by dates

My timers list looks like this: timer 1 => { startDate = 17/01/2019 11PM, endDate = 18/01/2019 9AM } timer 2 => { startDate = 18/01/2019 7AM, endDate = 18/01/2019 1PM } timer 3 => { startDate = 18/01/2019 12PM, endDate = 18/01/2019 10PM } time ...

Angular 14 debug error: Incorrect base path setting

Whenever I go for a run, I have to specify a starting point such as /pis/ ng serve --serve-path /pis/ Even after following these instructions, nothing seems to load. Can anyone lend a hand with setting a starting point in the ng serve process? ...

What makes TypeScript code run successfully using `node` instead of `ts-node` by mistake?

I have created a basic node.js project using TypeScript. Here is the content of my package.json file, which lists all the packages I have installed (without including ts-node): { "name": "mydemo", "version": "1.0.0", "description": "", "main": "ind ...

Context failing to refresh value upon route changes

My current context setup is as follows: import { createContext, ReactNode, useState } from "react"; type props = { children: ReactNode; }; type GlobalContextType = { name: string; setName: (value: string) => void; }; export const Glob ...

Putting DashJS to the test with Jest and Enzyme

Currently, I am facing a challenge while writing Jest tests for a React component that integrates a DashJS media player. To test the component, I have utilized Enzyme's mount method; however, it appears that there are issues with mounting the DashJS m ...

Setting up a Typescript project with a shared package configuration

Before I begin, there are a few premises to consider: I require a shared package that will be included in three other packages, TypeScript, Only one node modules, Ability for multiplatform usage (Windows / Linux), To utilize dependencies from the shared ...

Retrieving the Object value in Primeng p-dropdown when there is a change in selection

In my p-dropdown, I am trying to extract the selected value. <p-dropdown optionLabel="name" [options]="things" placeholder="Select Thing" [(ngModel)]="input" (onChange)="getValue(input)"></p-dropdown> typescript: //each lin ...