Creating a build task in Visual Studio Code with universal TypeScript compiler settings

Our project has the following structure:

+-- views
    +-- viewXXX
        +-- ts
        ¦    +-- controller.ts
        ¦    +-- helper.ts
        ¦    +-- ... (*.ts)
        +-- viewXXX.ctrl.js // this is the desired output file
        +-- viewXXX.ctrl.map.js
        +-- viewXXX.html

We are currently setting up a task in VSCode to compile following this structure...

// Task configuration for calling the Typescript compiler (tsc)
{
    "version": "0.1.0",
    "command": "tsc",
    "isShellCommand": true,
    "showOutput": "silent",
    "args": [
        "-t",
        "es5",
        "-m",
        "commonjs",
        "--sourceMap",
        "--out",
        "${fileDirname}.ctrl.js",
        // "--filesGlob", missing
        "${fileDirname}\\ts\\*.ts"
    ],
    "problemMatcher": "$tsc"
}

We're facing difficulties as there is no --filesGlob parameter available, or any other method to use regex to compile multiple files. Are there alternative approaches that support this workflow?

Answer №1

Upon thorough investigation, here is a functional solution :

  1. Utilize the provided package.json located at the root of your project directory
{
  "dependencies": {
    "gulp": "^3.9.0",
    "gulp-typescript": "^2.10.0",
    "gulp-sourcemaps": "^1.6.0"
  }
}
  1. npm install

  2. In the .vscode/task.json :

{
    "version": "0.1.0",
    "command": "gulp",
    "isShellCommand": true,
    "tasks": [
        {
            "taskName": "default",
            // Set this as the default build command.
            "isBuildCommand": true,
            // Display the output window only in case of unrecognized errors.
            "showOutput": "silent"
        }
    ]
}
  1. In the gulpfile.js placed at the root of your project directory :
var gulp = require('gulp');
var ts = require('gulp-typescript');
var sourcemaps = require('gulp-sourcemaps');

var views = [
  "views/view1",
  "views/view2"  
];

function buildView(viewBasePath) {
    var finalName = viewBasePath.split('/').pop();

    var tsResult = gulp.src(viewBasePath + '/ts/*.ts') 
        .pipe(sourcemaps.init())
        .pipe(ts({
            "module": "commonjs",
            "target": "es5",
            "out": finalName + '.ctrl.js'
        }));

    return tsResult.js
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(viewBasePath));
}

gulp.task('default', function () {
    for(var i = 0; i < views.length; i++) {
        buildView(views[i]);   
    }
});

To initiate build, use CTRL+SHIFT+B or set up a watch in the gulpfile.

Answer №2

To start, begin by establishing a tsconfig.json file in the main directory of your project :

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "inlineSourceMap": false,
    "sourceMap": true,
    "out": "${fileDirname}.ctrl.js"
  },
  "filesGlob": [
    "${fileDirname}\\ts\\*.ts"
  ]
}

Next, specify the location of the tsconfig.json using the "-p" parameter :

{
    "version": "0.1.0",
    "command": "tsc",
    "isShellCommand": true,
    "showOutput": "silent",
    "args": ["-p", "."],
    "problemMatcher": "$tsc"
}

Lastly, activate the task runner with CTRL+SHIFT+B.

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

Angular - Electron interface fails to reflect updated model changes

Whenever I click on a field that allows me to choose a folder from an electron dialog, the dialog opens up and I am able to select the desired folder. However, after clicking okay, even though the folder path is saved in my model, it does not immediately s ...

Creating bonds between components in React

As a newcomer to React JS, I am exploring how to implement event listeners in VanJS. For organizing my layout, I have decided to create separate components for elements like a panel and a button. Now, I am faced with the challenge of triggering a state c ...

Having difficulty constructing a full stack application using Express

I've been struggling to configure a full stack app using create-react-app with Express and TypeScript. My main issue is figuring out how to compile the server files into a build folder. I have separate tsconfig files for the server and create-react-ap ...

Managing asynchronous data using rxjs

I created a loginComponent that is responsible for receiving an email and password from the user, then making an HTTP request to retrieve the user data. My goal is to utilize this user data in other components through a service. Here is the login componen ...

Unveiling RxJs: The secret to extracting the notifier value using the takeuntil operator

I have a straightforward Rxjs timer set up that runs until a notifier emits a signal, it's pretty basic so far. enum TimerResult = { COMPLETE, ABORTED, SKIPPED }; _notifier: Subject<TimerResult> = new Subject(); notifier$: Observab ...

Storing the typeof result in a variable no longer aids TypeScript in type inference

Looking at the code snippet below: export const func = (foo?: number) => { const isNumber = typeof foo === 'number'; return isNumber ? Math.max(foo, 0) : 0; }; A problem arises when TypeScript complains that you cannot apply undefined to ...

Next.js API is throwing a TypeError because req.formData is not a recognized function

Below is the code snippet for the Next.js route I am working on: import { NextRequest, NextResponse } from 'next/server'; export const config = { runtime: 'edge', }; export default async function POST(req: NextRequest): Promise< ...

Retrieving chosen row data in Angular 6 Material Table

I am attempting to send the value of a selected row from one component to another upon clicking a button. However, in this particular example, I'm unsure where to obtain the selected row values and how to pass them on button click. After that, routing ...

When working with Typescript, an error may occur related to index types even though the constant object and its

I am struggling with understanding TypeScript, specifically when it comes to a problem I encountered. Hopefully, someone can shed some light on this for me. My issue revolves around a functional component that is responsible for displaying the correct com ...

Angular - handling Observable<T> responses when using Http.post

One issue I encountered was when trying to implement a method that returns an Observable. Within this method, I utilized http.post to send a request to the backend. My goal was to store the JSON object response in an Observable variable and return it. Howe ...

What causes the form to consistently show as invalid once it has been submitted?

register.html : <form [formGroup]="signupForm" (submit)="onSubmit()" class="form-detail"> <h2>Registration Form</h2> <div class="form-row-total"> <div class="form-row"> <in ...

When employing the pipe function within *ngFor, the webpage's refresh may vary, causing occasional updates

Utilizing angular2-meteor, I have already implemented pure: false. However, the pipe seems to be running inconsistently. For more details on the issue, please refer to my comments within the code. Thank you. <div *ngFor="#user of (users|orderByStatus) ...

Unraveling nested elements with the array map() method in Angular2 and Typescript: Fixing the issue of undefined property reference while mapping

Hey there! I'm currently working with Angular 4 and I have a piece of code that parses data from an API into a TypeScript array of rows. It's important to note that the code functions properly if elements like 'item.tceCampRun' and &apo ...

What is the process for modifying object information using string input in typescript?

How can I update an object's value in TypeScript based on a string input related to the object key? const objData = { // random value A: 11, B: 13, C: 53, innerObj: { AStatus: true, BStatus: false, CStatus: true, }, }; type Item ...

Getting the Angular component class reference within a triggered Highcharts selection event callback - what's the best approach?

It seems like I'm facing a common javascript closure issue, but let me illustrate it with a specific example as I'm struggling to grasp it in an Angular context. In my Angular component, I'm using the Highcharts library to visualize data. W ...

Best practices for transitioning a project from TypeScript 3 to TypeScript 4?

I am looking to upgrade my large monorepo, which was built using lerna, React, and TypeScript 3.7 around 2-3 years ago. My goal is to update it to TypeScript 4.8. Are there any tools available that can help me analyze and identify potential breaking chan ...

What is the method for obtaining the properties of a type as an array in Typescript?

In the given scenario: class Foo { constructor( private one: string, private two: string, private three: string) { } } Is there a way to create an array containing the type's properties? For example, I need to gene ...

After running npm install, I noticed that react-router-dom was installed as a separate package in a different package.json file. How can I ensure that it installs in the same

As a newcomer to React and VS Code, I am in need of a thorough explanation regarding dependencies and related concepts. After installing react-router-dom from the terminal, it generated a separate package.json file which has left me confused. I came acro ...

NG0900: Issue encountered while attempting to compare '[object Object]'. Please note that only arrays and iterable objects are permitted for comparison

Experimenting with an Angular project where I am retrieving data from a Minecraft API and displaying it on my website. This is my first time working with Angular's HTTP requests. Encountered the following error code; NG0900: Error trying to diff &apo ...

Explaining the process of defining an object type in TypeScript and the conversion from JavaScript

Currently, I am attempting to enhance the background of a React website developed in typescript (.tsx) by incorporating particles. My approach involves utilizing the particle-bg component available at: https://github.com/lindelof/particles-bg However, whe ...