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

Next.js is having trouble identifying the module '@types/react'

Every time I attempt to launch my Next.js app using npm run dev, an error notification pops up indicating that the necessary packages for running Next with Typescript are missing: To resolve this issue, kindly install @types/react by executing: np ...

Dealing with undefined arrays in Angular across multiple templates: Best practices

I'm currently developing a search screen for an application and I've come up with three possible outcomes for the results section. If the user hasn't searched yet, then show nothing. If the user searches and the array is empty, display "no ...

What is the best way to iterate over JSON data from an endpoint that contains multiple nested arrays using the .map() method?

Seeking to showcase weather API data from: () import Image from "next/image" interface Hour { time_epoch: number time: string temp_c: number temp_f: number is_day: number wind_mph: number wind_kph: number wind_deg ...

What are some strategies for circumventing the need for two switches?

My LayerEditor class consists of two private methods: export class LayerEditor { public layerManager: LayerManager; constructor() { this.layerManager = new LayerManager(this); } private executeCommand() { ...

Is your pure function component not receiving or responding to input props correctly?

Here is my code snippet: const actionCreators = { action: AppReducer.actionCreators.action } interface GlobalState { user: Model.User | null; } interface InputState { setStashBarWidth(width: number); stashWidth: number; } const Header = ...

Learn How to Implement Styling in Material UI using Styled Components

Utilizing styled-components with MaterialUI integration. Encountering the following error in LoginTextField component and seeking a resolution. Error Message: [ts] Type '{ width: number; }' is missing the following properties from type &apos ...

Typescript requires that the argument passed is undefined

Typescript: 2.4.1 I am exploring the creation of a helper function to produce redux action creators. Here is what I have: interface IAction<T extends string, P = undefined> { type: T; payload: P; } function createAction<T extends strin ...

Retrieve a mapping of keys from a generic object structure in TypeScript

I am trying to extract the key map from an object, and although I have created a function for this purpose, TypeScript is not happy with it. How can I resolve this issue without using acc: any? const origin = { a: 1, b: 'string', c: () =&g ...

Update name of an angular 2 component template

Is it possible to dynamically change the component template <FAQ-omni></FAQ-omni> based on a click event in the list? <div class="row"> <div class="col-xlg-4 col-xl-12 col-lg-12 col-md-7 col-sm-12 col-xs-12" title="FAQ" baCard ...

Unable to download tsc through the Terminal on OS X

Struggling to install tsc, encountering numerous errors upon running it. Reinstalled node and npm multiple times, adjusted npm flag to verbose, here's the output: Mitch:~ mitch$ npm install -g typescript npm info it worked if it ends with ok ... Fe ...

Guide on Applying a Dynamic Color in VueJs 3 Composition API/Vuetify Using CSS

Currently, my project utilizes Vue 3 with the composition API and Vuetify for the UI. I am looking to utilize a color that is already defined in a Vuetify theme variable within my CSS, similar to how I have done it previously in JavaScript. Although I at ...

Don't initialize each variable within the constructor of a class, find a more efficient approach

I have a collection of JavaScript classes representing different models for my database. Each model contains attributes such as name, email, and password. Is there a more efficient way to create a new User instance without manually assigning values to ea ...

What specific type should be used for validations when incorporating express-validator imperative validations?

Having trouble implementing express-validator's imperative validations in TypeScript because the type for validations cannot be found. // reusable function for multiple routes const validate = validations => { return async (req, res, next) => ...

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 ...

The FirebaseX Ionic native plugin received 2 arguments instead of the expected 3-4

Trying to implement Firebase Phone Auth with the FirebaseX plugin, I encountered an issue. Here is the code snippet I used: async getVerificationCode(): void { const res:any = await this.firebaseX.verifyPhoneNumber('+16505553434', 60); ...

Building a TypeScript Rest API with efficient routing, controllers, and classes for seamless management

I have been working on transitioning a Node project to TypeScript using Express and CoreModel. In my original setup, the structure looked like this: to manage users accountRouter <- accountController <- User (Class) <- CoreModel (parent Class o ...

Tips for fixing the TS2345 compilation error when working with React

Attempting to implement the setState method in React has resulted in a compile error. Any solutions to this issue would be greatly appreciated. Frontend: react/typescript articleApi.tsx import axios from 'axios'; import {Article} from '../ ...

What could be causing these Typescript compilation errors I am experiencing?

I am puzzled by the appearance of these errors, especially since I copied the entire ClientApp folder from a running application where they did not exist. Here is the structure of my project: This is my package.json file: { "name": "crossvertise-calan ...

Encountering an unanticipated DOMException after transitioning to Angular 13

My Angular project is utilizing Bootstrap 4.6.2. One of the components features a table with ngb-accordion, which was functioning properly until I upgraded the project to Angular 13. Upon accessing the page containing the accordion in Angular 13, I encount ...

When utilizing Typescript to develop a form, it is essential to ensure that the operand of a 'delete' operator is optional, as indicated by error code ts(279

Can someone help me understand why I am encountering this error? I am currently working on a form for users to submit their email address. export const register = createAsyncThunk< User, RegisterProps, { rejectValue: ValidationErrors; } > ...