grunt-ts

Compile and manage your TypeScript project

grunt-ts

Grunt-ts is an npm package that handles TypeScript compilation work in GruntJS build scripts. It provides a Grunt-compatible wrapper for the tsc command-line compiler, and provides some additional functionality that improves the TypeScript development workflow. Grunt-ts is itself written in TypeScript.

If you've never used GruntJS on your computer, you should follow the detailed instructions here to get Node.js and the grunt-cli working. If you're a Grunt expert, simply follow these steps:

  • Run npm install grunt-ts in your project directory; this will install grunt-ts, TypeScript, and GruntJS.
  • Add the ts task in your Gruntfile.js (see below for a minimalist one).
  • Run grunt at the command line in your project folder to compile your TypeScript code.

This minimalist Gruntfile.js will compile *.ts files in all subdirectories of the project folder, excluding anything under node_modules:

module.exports = function(grunt) {
  grunt.initConfig({
    ts: {
      default : {
        src: ["**/*.ts", "!node_modules/**/*.ts"]
      }
    }
  });
  grunt.loadNpmTasks("grunt-ts");
  grunt.registerTask("default", ["ts"]);
};

A more extensive sample Gruntfile.js is available here.

  • Allows use of all standard GruntJS functionality such as use of customizable task targets, globbing, use of the files object (for instantiating multiple independent tsc runs in a single target), etc.
  • Allows the developer to select a custom TypeScript compiler version for their project, or even use a custom (in-house) version.
  • Supports most switches of the tsc TypeScript Compiler via options in the gruntfile ts task, and also supports switch overrides per-target.
  • Provides a transforms feature that eases code refactoring by taking the burden of relative path maintenance off the developer. If the paths to a set of files changes, grunt-ts will regenerate the relevant sections. This feature supports:
  • Allows concatenation where supported by the TypeScript compiler's --out switch
  • Encodes HTML files as TypeScript variables (for HTML templating engines)
  • Performs live file watching (compile on save)
  • Enables "Fast" compile when using external modules

Grunt-ts supports most tsc switches. Click the link to cross-reference to the grunt-ts option.

tsc switchgrunt-ts analoguedescription
--declarationdeclarationGenerates a .d.ts definitions file for compiled TypeScript files
--mapRoot LOCATIONmapRootSpecifies the location where debugger should locate map files instead of generated locations.
--module KINDmoduleSpecify module style for code generation
--noImplicitAnynoImplicitAnyWarn on expressions and declarations with an implied any type.
--noResolvenoResolveSkip resolution and preprocessing (deprecated)
--out FILEoutConcatenate and emit output to a single file.
--outDir DIRECTORYoutDirRedirect output structure to the directory.
--preserveConstEnumspreserveConstEnumsConst enums will be kept as enums in the emitted JS.
--removeCommentsremoveCommentsConfigures if comments should be included in the output
--sourceMapsourceMapGenerates corresponding .map file
--sourceRoot LOCATIONsourceRootSpecifies the location where debugger should locate TypeScript files instead of source locations.
--suppressImplicitAnyIndexErrorssuppressImplicitAnyIndexErrorsSpecifies the location where debugger should locate TypeScript files instead of source locations.
--target VERSIONtargetSpecify ECMAScript target version: 'es3', 'es5', or 'es6'

For file ordering, look at JavaScript Generation.

propertywhere to definedescription
commentsoptiontrue, false (default) - include comments in emitted JS.
compileoptiontrue (default), false - compile TypeScript code.
compileroptionstring - path to custom compiler
declarationoptiontrue, false (default) - indicates that definition files should be emitted.
failOnTypeErrorsoptiontrue (default), false - fail Grunt pipeline if there is a type error
fastoption'watch' (default), 'always', 'never' - how to decide on a "fast" grunt-ts compile.
filestargetSets of files to compile and optional output destination
htmltargetstring or string[] - glob to HTML templates
htmlModuleTemplateoptionstring - HTML template namespace
htmlVarTemplateoptionstring - HTML property name
mapRootoptionstring - root for referencing .js.map files in JS
moduleoption'amd' (default) or 'commonjs' - specifies external module style
noImplicitAnyoptiontrue, false (default) - enable for stricter type checking
noResolveoptiontrue, false (default) - for deprecated version of TypeScript
optionstarget
outtargetstring - instruct tsc to concatenate output to this file.
outDirtargetstring - instruct tsc to emit JS to this directory.
preserveConstEnumsoptiontrue, false (default) - If true, const enums will be kept as enums in the emitted JS.
referencetargetstring - tells grunt-ts which file to use for maintaining references
removeCommentsoptiontrue (default), false - removes comments in emitted JS
sourceRootoptionstring - root for referencing TS files in .js.map
sourceMapoptiontrue (default), false - indicates if source maps should be generated (.js.map)
suppressImplicitAnyIndexErrorsoptionfalse (default), true - indicates if TypeScript should allow access to properties of an object by string indexer when --noImplicitAny is active, even if TypeScript doesn't know about them.
srctargetstring or string[] - glob of TypeScript files to compile.
targetoption'es5' (default), 'es3', or 'es6' - targeted ECMAScript version
verboseoptiontrue, false (default) - logs tsc command-line options to console
watchtargetstring - will watch for changes in the specified directory or below

Note: In the above chart, if "where to define" is "target", the property must be defined on a target or on the ts object directly. If "where to define" is "options", then the property must be defined on an options object on ts or on a target under ts.

Grunt-ts does not support the GruntJS standard dest target property. Instead, you should use files, out, or outDir.

Grunt-ts supports use of the GruntJS-centric files property on a target as an alternative to the tsc-centric use of src and out/outDir.

Notes:

  • The fast grunt-ts option is not supported in this configuration. You should specify fast: 'never' to avoid warnings when files is used.
  • It is not supported to specify an array of values for dest with grunt-ts. A warning will be issued to the console. If a non-empty array is passed, the first element will be used and the rest will be truncated.
  • If the dest parameter ends with ".js", the value will be passed to the --out parameter of the TypeScript compiler. Otherwise, if there is a non-blank value, it will be passed to the --outDir parameter.
  • If you intend to pass the specific value "src" to the TypeScript --outDir parameter, specify it as "src/" in the dest parameter to avoid grunt-ts warnings.

Here are some examples of using the target files property with grunt-ts:

grunt.initConfig({
  ts: {
    compileTwoSetsOfFilesUsingArrayStyle: {
      // This will run tsc twice.  The first time, the result of the 'files1/**/*.ts' glob will be 
      // passed to tsc with the --out switch as 'out/ArrayStyle/1.js'. 
      // see https://github.com/gruntjs/grunt-docs/blob/master/Configuring-tasks.md#files-array-format 
      files: [{ src: ['files1/**/*.ts'], dest: 'out/ArrayStyle/1.js' },
              { src: ['files2/**/*.ts'], dest: 'out/ArrayStyle/2.js' }],
      options: {
        fast: 'never'
      }
    },
    compileTwoSetsOfFilesToDirUsingArrayStyle: {
      // This will run tsc twice.  The first time, the result of the 'files1/**/*.ts' glob will be 
      // passed to tsc with the --outDir switch as 'out/ArrayStyle'. 
      // see https://github.com/gruntjs/grunt-docs/blob/master/Configuring-tasks.md#files-array-format 
      files: [{ src: ['files1/**/*.ts'], dest: 'out/ArrayStyle' },
              { src: ['files2/**/*.ts'], dest: 'out/ArrayStyle' }],
      options: {
        fast: 'never'
      }
    },
    compileTwoSetsOfFilesUsingObjectStyle: {
      // This will run tsc twice.  The first time, the result of the 'files1/**/*.ts' glob will be 
      // passed to tsc with the --out switch as 'out/ObjectStyle/1.js'. 
      // see https://github.com/gruntjs/grunt-docs/blob/master/Configuring-tasks.md#files-object-format 
      files: {
        'out/ObjectStyle/1.js': ['files1/**/*.ts'],
        'out/ObjectStyle/2.js': ['files2/**/*.ts']
      },
      options: {
        fast: 'never'
      }
    },
    compileTwoSetsOfFilesToDirUsingObjectStyle: {
      // This will run tsc once.  The result of the globs will be passed to tsc with the 
      // --outDir switch as 'out/ObjectStyle'. 
      // see https://github.com/gruntjs/grunt-docs/blob/master/Configuring-tasks.md#files-object-format 
      files: {
        'out/ObjectStyle': ['files1/**/*.ts','files2/**/*.ts']
        },
        options: {
          fast: 'never'
        }
      }
    }
});

Grunt-ts supports compilation of .html file content to TypeScript variables which is explained in detail here. The html target property acts similarly to src, except that it searches for html files to convert to TypeScript variables. See also htmlModuleTemplate and htmlVarTemplate.

// How to use the html target property (incomplete example) 
grunt.initConfig({
  ts: {
    default: {
      html: ["templates/**/*.html"]
    }
  }
});

Note: the html compilation functionality will not fire if the src property is not specified. If you wish to only have the HTML compile to TypeScript without compiling the resulting .ts files to JavaScript, make sure they're excluded from the src globs, or else specify an empty src array alongside the html task property, and set the target compile option to false:

// Example of how to compile html files to TypeScript without compiling the resulting 
// .ts files to JavaScript. 
grunt.initConfig({
  ts: {
    default: {
      html: ["templates/**/*.html"],
      src: [],
      options: {
        compile: false
      }
    }
  }
});

This section allows global configuration for the grunt-ts task. All target-specific options are supported. If a target also has options set, the target's options override the global task options.