How to update the tsconfig.json file within a VS2019 project using MSBuild?

I am working with a Visual Studio solution that contains multiple tsconfig.json files and I would like them to have different behaviors in production.

My plan is to create two additional files for this purpose:

  1. tsconfig.json will contain the default settings for this section of the solution:
{
  "compilerOptions": {
    "sourceMap": true,
    "removeComments": false,
    ...
  },
  ... many more settings
}
  1. tsconfig.release.json will override those settings to exclude comments and source maps:
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "sourceMap": false,
    "removeComments": true
  }
}

How do I instruct VS2019/MSBuild to utilize the tsconfig.release.json overrides during a release build or publish process?

Answer №1

I've come up with a workaround for this issue, although it's not ideal and I would be grateful for a better solution.

One approach is to use custom config file names with the tsc command, but it requires specific adjustments within MSBuild by including

<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
in the project file along with additional configurations to execute it.

MSBuild allows for different settings between Release and Debug modes, but only if it controls all TypeScript configurations and there are no instances of tsconfig.json files within the project structure.

While MSBuild can locate any tsconfig.json file at any level of folder depth, alternative file names such as tsconfig.release.json or tsconfig.debug.json cannot be identified.

Furthermore, MSBuild has the ability to adjust inclusion rules for files, leading to the following solution:

  • Reposition the release overrides to a designated folder so that tsconfig.release.json becomes releaseConfig/tsconfig.json. This will necessitate adjustments to relative paths in order to locate the project:
{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "sourceMap": false,
    "removeComments": true
  },
  "include": [ "../**/*" ]
}
  • Two modifications are required in the .csproj file. Firstly, prevent this configuration from being utilized in non-release builds:
<ItemGroup Condition="'$(Configuration)|$(Platform)'!='Release|AnyCPU'">
    <Content Remove="whatever\releaseConfig\tsconfig.json" />
    <None Include="whatever\releaseConfig\tsconfig.json" />
</ItemGroup>
  • Lastly, for the release build, switch the file references:
<ItemGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
    <Content Remove="whatever\tsconfig.json" />
    <None Include="whatever\tsconfig.json" />
    <None Remove="whatever\releaseConfig\tsconfig.json" />
</ItemGroup>

The default tsconfig.json is taken out of <Content>, but must be included under <None> to maintain the appropriate relative paths in releaseConfig\tsconfig.json.

Answer №2

Encountered a similar issue and delved into the depths of the TypeScript NuGet package. I ultimately settled on the following solution, which I added to Directory.Build.targets in a higher-level directory.

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Target Name="FindConfigFiles"
          Condition="'$(DesignTimeBuild)' != 'true'">
    <ItemGroup>
      <ConfigFiles Include="**\tsconfig.json" KeepDuplicates="false" 
                   Condition="'$(Configuration)' == 'Release'" />
      <ConfigFiles Include="**\tsconfig.Development.json" KeepDuplicates="false"
                   Condition="'$(Configuration)' == 'Debug'" />
    </ItemGroup>
  </Target>
</Project>

I specified explicit file names, but for those who landed here through a search engine, I have added **\ before the Includes (to match in any subdirectory).

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

Optimal method for writing to JSON file in NodeJS 10 and Angular 7?

Not sure if this question fits here, but it's really bothering me. Currently using Node v10.16.0. Apologies! With Angular 7, fs no longer functions - what is the optimal method to write to a JSON file? Importing a JSON file is now simple, but how ca ...

You cannot directly access an array useState by index in React js, but you can use the map function to

export interface JobListing { id: number, isTraded: boolean, feedback: string, title: string, message: string, skills: string[], sender: string, ipAddress: string } const GroupList = () => { const [jobListings, setJobListings] = useSt ...

Creating an Angular form group that includes dynamic form controls with custom form control names

Seeking to implement a formGroup that dynamically adjusts based on JSON data like this: const LIMITS: Limit[] = [ { id: 'limit1', value: 1000, disabled: false }, { id: 'limit2', value: 500, disabled: tru ...

retrieving JSON data within HTML elements

How can I access the JSON values {{u.login}} from HTML instead of just through JavaScript? Currently, I am only able to access them using JS. Is there a way to directly access JSON values in HTML? At the moment, I am getting them as text. Could you please ...

Learn how to generate specific error messages based on the field that caused the failure of the @Column({ unique: true }) Decorator. Error code 23505

Hey there! I'm currently facing an issue while trying to handle Sign Up exceptions in my code. I want to inform the user if their username OR email is already in use. Although using the decorator @Column({ unique: true}) allows me to catch error 23505 ...

Exploring Cypress: Leveraging the Power of Variable Assignment

Recently, I encountered an issue while working with a variable in a Cypress each loop. Despite incrementing the variable within the loop, it resets to zero once outside of it. Can someone shed light on why this happens and suggest a solution? Thank you. p ...

Is there a way to differentiate between a plain object and a class instance in Typescript?

Specifically, I am looking to differentiate between primitive types and plain objects versus class instances. let x = {y:5} // this is acceptable class X { y = 5; } let x = new X(); // this is not permissible ...

Exploring the Power of PrimeNG and Observables in Angular 4 with RxJS

After configuring my Angular 4 project with a service like this: const usersURL = 'http://my.super.url.php'; @Injectable() export class UserService { users: Observable<User[]> constructor (public http:Http) let tick$ = Observ ...

Retrieve type definitions for function parameters from an immutable array containing multiple arrays

My current challenge involves implementing a function similar to Jest's test.each iterator: // with "as const" forEach([ [ 1, 2, 3 ], [ "a", "b", "c" ], ] as const, (first, second, third) => { // ...

Angular: Identifier for Dropdown with Multiple Selection

I have recently set up a multi select dropdown with checkboxes by following the instructions provided in this post: https://github.com/NileshPatel17/ng-multiselect-dropdown This is how I implemented it: <div (mouseleave)="showDropDown = false" [class. ...

The IntrinsicAttributes type does not include the property 'path' in the Preact router

I am facing a challenge while developing my website using preact router. Every time I try to add something to the router, I encounter an error stating "Property 'path' does not exist on type 'IntrinsicAttributes'." Despite this error, t ...

What is preventing the getters for form errors from functioning in my Angular Reactive Form component template, while a direct reference does work?

I have a question regarding a small issue with an Angular reactive form in a lazily loaded signup module. The code structure is structured as follows: TS get email() { return this.myForm.get('email'); } // While this code works from within th ...

Encountered an issue when attempting to send data using this.http.post in Angular from the client's perspective

Attempting to transfer data to a MySQL database using Angular on the client-side and Express JS on the server-side. The post function on the server side works when tested with Postman. Here is the code snippet: app.use(bodyParser.json()); app.use(bodyPa ...

What is the reason behind Rxjs switchMap only emitting the final value from an of() observable source?

Here are two code snippets, one using map and the other using switchMap. The functionality of map is clear: of('foo', 'bar') .pipe(map((val) => sanitizer(val))) .subscribe((val) => console.log('value:', val)); func ...

Received an unexpected argument count of 1 instead of the expected 0 while passing a function as a prop to a child component

I transferred the deleteImgfunc function from the insertFarmDiaryDetail component to the InsertFarmDiarySubPage component, which acts as a child component. DeleteImgfunc is a parameter-receiving function. Despite creating an interface and defining paramet ...

A guide on transforming a 1-dimensional array into a 2-dimensional matrix layout using Angular

My query revolves around utilizing Template (HTML) within Angular. I am looking for a way to dynamically display an array of objects without permanently converting it. The array consists of objects. kpi: { value: string; header: string; footer: string }[] ...

The unpredictable behavior of the `this` keyword while troubleshooting a TypeScript program in VS code

Upon further investigation, it seems that the issue I encountered was related to using Chrome for debugging my full application. This led me to question whether the problem stemmed from TypeScript or VS Code. Before submitting my findings, I decided to sw ...

What is the appropriate overload to be selected when utilizing a ref in the method call?

Encountering an unfamiliar TS error while working with the code snippet below: <script lang="ts"> import {defineComponent, computed, toRef} from 'vue' import _ from 'lodash' import {DateTime} from 'luxon' int ...

Bundle Angular library exports along with its corresponding models

I am in the process of developing an angular library for our company's private npm repository. Within this library, I aim to export classes that are utilized (injected via @Input()) in the library components. Here is a sample model: export class AdsT ...

guide to utilizing npm/yarn with tsx react

I've recently made the switch to using TypeScript with React, but I'm encountering a problem. After installing certain packages from npm or yarn, I'm having trouble using them in my .tsx components. The error message suggests looking for @ty ...