Core TypeScript compilation functionality providing a comprehensive Grunt-compatible wrapper around the TypeScript compiler (tsc) with advanced build configurations and error handling.
Configure TypeScript compilation using Grunt's standard multi-task pattern with target-specific options.
/**
* Main task configuration structure
*/
interface TaskConfiguration {
ts: {
[targetName: string]: ITargetOptions & {
options?: ITaskOptions;
};
};
}
interface ITargetOptions {
/** TypeScript files to compile (supports globbing) */
src?: string[];
/** Output file for concatenated JavaScript (uses tsc --out) */
out?: string;
/** Output directory for compiled JavaScript files (uses tsc --outDir) */
outDir?: string;
/** Path to reference.ts file for maintaining references */
reference?: string;
/** Base directory for maintaining source structure when using outDir */
baseDir?: string;
/** Task-specific compiler options */
options?: ITaskOptions;
}Usage Example:
grunt.initConfig({
ts: {
// Development target
dev: {
src: ["src/**/*.ts"],
outDir: "built/",
options: {
target: "es5",
module: "commonjs",
sourceMap: true,
fast: "watch"
}
},
// Production target
prod: {
src: ["src/**/*.ts"],
out: "dist/app.js",
options: {
target: "es5",
removeComments: true,
sourceMap: false,
fast: "never"
}
}
}
});All TypeScript compiler options are supported through the options object.
interface ITaskOptions {
// ECMAScript target version
target?: "es3" | "es5" | "es6";
// Module format for code generation
module?: "amd" | "commonjs" | "umd" | "system" | "es6" | "es2015";
// Generate corresponding .d.ts files
declaration?: boolean;
// Generate source map files
sourceMap?: boolean;
// Inline source maps instead of separate .js.map files
inlineSourceMap?: boolean;
// Include TypeScript sources in source maps
inlineSources?: boolean;
// Output directory for compiled files
outDir?: string;
// Remove comments from compiled output
removeComments?: boolean;
// Warn on expressions with implied 'any' type
noImplicitAny?: boolean;
// Do not emit JavaScript if there are type errors
noEmitOnError?: boolean;
// Preserve const enums in emitted JavaScript
preserveConstEnums?: boolean;
// Suppress implicit any index errors when using --noImplicitAny
suppressImplicitAnyIndexErrors?: boolean;
// Enable experimental support for decorators
experimentalDecorators?: boolean;
// Emit metadata for decorators (used by Angular, etc.)
emitDecoratorMetadata?: boolean;
// JSX code generation style
jsx?: "preserve" | "react";
// Module resolution strategy
moduleResolution?: "node" | "classic";
// Allow JavaScript files to be compiled
allowJs?: boolean;
// Do not emit 'use strict' directives in module output
noImplicitUseStrict?: boolean;
// Report errors for fallthrough cases in switch statements
noFallthroughCasesInSwitch?: boolean;
// Report error when not all code paths return a value
noImplicitReturns?: boolean;
// Do not report errors on unreachable code
allowUnreachableCode?: boolean;
// Do not report errors on unused labels
allowUnusedLabels?: boolean;
// Disallow inconsistently-cased references to the same file
forceConsistentCasingInFileNames?: boolean;
// Stylize errors and messages using color and context
pretty?: boolean;
// Root directory for calculating relative paths
rootDir?: string;
// Location where debugger should locate map files
mapRoot?: string;
// Location where debugger should locate TypeScript files
sourceRoot?: string;
// Specify locale for error messages
locale?: string;
// Do not include default library file in compilation
noLib?: boolean;
// Do not add triple-slash references or module imports to compilation
noResolve?: boolean;
// Do not generate custom helper functions like __extends
noEmitHelpers?: boolean;
// Skip default library declaration file type checking
skipDefaultLibCheck?: boolean;
// Newline character to use: 'CRLF' or 'LF'
newLine?: "CRLF" | "LF";
// Enable support for experimental async functions
experimentalAsyncFunctions?: boolean;
// Make cases that break single-file transpilation into errors
isolatedModules?: boolean;
// Do not emit even if no errors
noEmit?: boolean;
// Do not emit members marked as @internal
stripInternal?: boolean;
// Disable strict object literal assignment checking
suppressExcessPropertyErrors?: boolean;
// Allow synthetic default imports for ES6-style imports with pre-ES6 libraries
allowSyntheticDefaultImports?: boolean;
// Specify object invoked for createElement when targeting 'react' JSX
reactNamespace?: string;
}Additional options provided by grunt-ts for enhanced functionality.
interface GruntTSSpecificOptions {
// Whether to compile TypeScript (can disable for transforms-only runs)
compile?: boolean; // default: true
// Fast compilation mode
fast?: "never" | "always" | "watch"; // default: "watch"
// Fail Grunt pipeline on TypeScript type errors
failOnTypeErrors?: boolean; // default: true
// Log tsc command-line options to console
verbose?: boolean; // default: false
// Emit Grunt events on build failure for pipeline integration
emitGruntEvents?: boolean; // default: false
// Path to custom TypeScript compiler
compiler?: string;
// Additional flags to pass directly to tsc
additionalFlags?: string;
// Preserve comments in output (opposite of removeComments)
comments?: boolean; // default: false
}Usage Example:
ts: {
dev: {
src: ["src/**/*.ts"],
options: {
target: "es5",
module: "commonjs",
sourceMap: true,
fast: "watch",
verbose: true,
failOnTypeErrors: false // Continue on type errors
}
}
}The compilation process handles TypeScript files through several phases.
/**
* Main compilation function that processes all TypeScript files
* @param options - Complete grunt-ts options
* @param compilationInfo - File compilation details
* @returns Promise resolving to compilation result
*/
function compileAllFiles(
options: IGruntTSOptions,
compilationInfo: IGruntTSCompilationInfo
): Promise<ICompileResult>;
interface ICompileResult {
/** Exit code from TypeScript compiler (0 = success) */
code: number;
/** Compiler output including errors and warnings */
output: string;
/** Number of TypeScript files compiled */
fileCount?: number;
}
interface IGruntTSCompilationInfo extends grunt.file.IFilesConfig {
/** Output directory for compiled files */
outDir?: string;
/** Single output file for concatenated JavaScript */
out?: string;
/** Array of TypeScript source files to compile */
src?: string[];
/** Glob patterns used to find source files */
glob?: string[];
}grunt-ts categorizes TypeScript compilation errors and provides detailed reporting.
// Error categorization (internal)
interface ErrorCategories {
/** Syntax errors that prevent JavaScript emission */
level1ErrorCount: number;
/** Compiler flag misuse errors that prevent JavaScript emission */
level5ErrorCount: number;
/** Type errors that don't prevent JavaScript emission */
nonEmitPreventingWarningCount: number;
/** Whether TypeScript 7017 error (implicit any index) was found */
hasTS7017Error: boolean;
}
// Build result determination
interface BuildResult {
/** Whether the build should be considered successful */
isSuccessfulBuild: boolean;
/** Whether errors are only type-related (no syntax/flag errors) */
isOnlyTypeErrors: boolean;
}Error Types:
Use a custom TypeScript compiler version or build.
interface CustomCompilerOptions {
/** Path to custom TypeScript compiler's main JS file */
compiler?: string;
}Usage Example:
ts: {
custom: {
src: ["src/**/*.ts"],
options: {
compiler: './custom-typescript/bin/tsc'
}
}
}grunt-ts supports Grunt's files configuration for multiple independent compilation runs.
// Array format
interface FilesArrayConfig {
files: Array<{
src: string[];
dest: string; // .js extension = --out, otherwise = --outDir
}>;
}
// Object format
interface FilesObjectConfig {
files: {
[dest: string]: string[]; // dest -> src files mapping
};
}Usage Example:
ts: {
multipleBuilds: {
files: [
{ src: ['client/**/*.ts'], dest: 'built/client.js' },
{ src: ['server/**/*.ts'], dest: 'built/server/' }
],
options: {
fast: 'never' // Required when using files configuration
}
}
}