Search code examples
typescriptvisual-studio-codetsc

Set up build task in vscode with global tsc parameters


We have the following project 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 trying to configure a task in VSCode that allows to compile following this structure...

// A task runner that calls 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"
}

And we are not able to make it work because there is no --filesGlob parameter, or any other way to pass a regex to compile many files. Any other approach that allows this workflow??


Solution

  • After doing some research, here is a working solution :

    1. Use the following package.json 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",
                // Make this the default build command.
                "isBuildCommand": true,
                // Show the output window only if unrecognized errors occur.
                "showOutput": "silent"
            }
        ]
    }
    
    1. In the gulpfile.js 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]);   
        }
    });
    

    And if you want to build, use the combination CTRL+SHIFT+B or install a watch in the gulpfile.