Transpile TypeScript code to JavaScript with Closure annotations.
npx @tessl/cli install tessl/npm-tsickle@0.46.00
# Tsickle
1
2
Tsickle is a TypeScript to Closure Compiler translator that converts TypeScript code into a form acceptable to Google's Closure Compiler. It enables developers to write in TypeScript while taking advantage of Closure Compiler's advanced optimization capabilities by automatically generating Closure-compatible JSDoc annotations, converting ES6 modules to goog.module format, generating externs.js from TypeScript declaration files, translating export statements and enums into Closure-compatible forms, and reprocessing JSDoc comments to ensure compatibility.
3
4
## Package Information
5
6
- **Package Name**: tsickle
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install tsickle`
10
11
## Core Imports
12
13
```typescript
14
import { emit, TsickleHost, EmitResult } from "tsickle";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { emit, TsickleHost, EmitResult } = require("tsickle");
21
```
22
23
## Basic Usage
24
25
```typescript
26
import * as ts from "typescript";
27
import { emit, TsickleHost } from "tsickle";
28
29
// Create TypeScript program
30
const program = ts.createProgram(["src/index.ts"], {
31
rootDir: "/project/src",
32
target: ts.ScriptTarget.ES2015,
33
module: ts.ModuleKind.CommonJS
34
});
35
36
// Configure tsickle host
37
const host: TsickleHost = {
38
shouldSkipTsickleProcessing: (fileName) => false,
39
shouldIgnoreWarningsForPath: (filePath) => false,
40
pathToModuleName: (context, importPath) => importPath.replace(/\.tsx?$/, ''),
41
fileNameToModuleId: (fileName) => fileName,
42
googmodule: true,
43
transformTypesToClosure: true,
44
generateExtraSuppressions: true
45
};
46
47
// Emit transformed code
48
const result = emit(program, host, (fileName, content) => {
49
console.log(`Writing ${fileName}`);
50
require('fs').writeFileSync(fileName, content);
51
});
52
53
if (result.diagnostics.length > 0) {
54
console.error("Compilation errors:", result.diagnostics);
55
}
56
```
57
58
## Architecture
59
60
Tsickle is built around several key components:
61
62
- **Core Transformation**: The main `emit()` function orchestrates the entire transformation pipeline
63
- **Type Translation**: Converts TypeScript types to Closure Compiler JSDoc annotations
64
- **Module System**: Transforms CommonJS and ES6 modules to goog.module format
65
- **Decorator Processing**: Handles decorator downleveling and property renaming for Closure compatibility
66
- **JSDoc Management**: Parses, transforms, and generates Closure-compatible JSDoc comments
67
- **Externs Generation**: Creates extern definitions from TypeScript ambient declarations
68
- **Host Interface**: Configurable host system for customizing transformation behavior
69
70
## Capabilities
71
72
### Core Transformation
73
74
Main transformation functionality that converts TypeScript programs into Closure-compatible JavaScript with proper JSDoc annotations and module formatting.
75
76
```typescript { .api }
77
function emit(
78
program: ts.Program,
79
host: TsickleHost,
80
writeFile: ts.WriteFileCallback,
81
targetSourceFile?: ts.SourceFile,
82
cancellationToken?: ts.CancellationToken,
83
emitOnlyDtsFiles?: boolean,
84
customTransformers?: EmitTransformers
85
): EmitResult;
86
87
function mergeEmitResults(emitResults: EmitResult[]): EmitResult;
88
89
interface TsickleHost extends GoogModuleProcessorHost, TsMigrationExportsShimProcessorHost, AnnotatorHost {
90
transformDecorators?: boolean;
91
transformTypesToClosure?: boolean;
92
generateTsMigrationExportsShim?: boolean;
93
addDtsClutzAliases?: boolean;
94
shouldSkipTsickleProcessing(fileName: string): boolean;
95
shouldIgnoreWarningsForPath(filePath: string): boolean;
96
googmodule: boolean;
97
useDeclarationMergingTransformation?: boolean;
98
generateExtraSuppressions: boolean;
99
}
100
```
101
102
[Core Transformation](./core-transformation.md)
103
104
### Type Translation
105
106
Advanced type translation system that converts TypeScript type annotations into Closure Compiler-compatible JSDoc type expressions.
107
108
```typescript { .api }
109
class TypeTranslator {
110
constructor(host: AnnotatorHost, typeChecker: ts.TypeChecker, node: ts.Node, isForExterns?: boolean);
111
translate(type: ts.Type): string;
112
symbolToString(sym: ts.Symbol): string;
113
isAlwaysUnknownSymbol(symbol: ts.Symbol): boolean;
114
}
115
116
function typeToDebugString(type: ts.Type): string;
117
function symbolToDebugString(sym: ts.Symbol): string;
118
```
119
120
[Type Translation](./type-translation.md)
121
122
### Module System Transformation
123
124
Converts CommonJS require() imports to goog.module() and goog.require() calls, with support for ES6 module syntax transformation.
125
126
```typescript { .api }
127
interface GoogModuleProcessorHost {
128
pathToModuleName(context: string, importPath: string): string;
129
fileNameToModuleId(fileName: string): string;
130
isJsTranspilation?: boolean;
131
}
132
133
function commonJsToGoogmoduleTransformer(
134
host: GoogModuleProcessorHost,
135
modulesManifest: ModulesManifest,
136
typeChecker: ts.TypeChecker
137
): ts.TransformerFactory<ts.SourceFile>;
138
```
139
140
[Module System](./module-system.md)
141
142
### JSDoc Processing
143
144
Comprehensive JSDoc parsing, transformation, and generation system for maintaining Closure Compiler compatibility.
145
146
```typescript { .api }
147
interface ParsedJSDocComment {
148
tags: Tag[];
149
warnings?: string[];
150
}
151
152
function parse(comment: ts.CommentRange): ParsedJSDocComment;
153
function parseContents(commentText: string): ParsedJSDocComment;
154
function toString(tags: Tag[], escapeExtraTags?: boolean): string;
155
```
156
157
[JSDoc Processing](./jsdoc-processing.md)
158
159
### Decorator Support
160
161
Handles decorator downleveling and output transformation for Closure Compiler property renaming compatibility.
162
163
```typescript { .api }
164
function decoratorDownlevelTransformer(
165
typeChecker: ts.TypeChecker,
166
diagnostics: ts.Diagnostic[]
167
): ts.TransformerFactory<ts.SourceFile>;
168
169
function shouldLower(decorator: ts.Decorator, typeChecker: ts.TypeChecker): boolean;
170
function hasExportingDecorator(node: ts.Node, typeChecker: ts.TypeChecker): boolean;
171
```
172
173
[Decorator Support](./decorator-support.md)
174
175
### Externs Generation
176
177
Generates Closure Compiler extern definitions from TypeScript ambient declarations and .d.ts files.
178
179
```typescript { .api }
180
function generateExterns(
181
typeChecker: ts.TypeChecker,
182
sourceFile: ts.SourceFile,
183
host: AnnotatorHost,
184
moduleResolutionHost: ts.ModuleResolutionHost,
185
options: ts.CompilerOptions
186
): { output: string; diagnostics: ts.Diagnostic[] };
187
188
function getGeneratedExterns(
189
externs: { [fileName: string]: string },
190
rootDir: string
191
): string;
192
```
193
194
[Externs Generation](./externs-generation.md)
195
196
### Transformer Utilities
197
198
Core utilities for AST manipulation and transformation support, including helper functions for working with TypeScript nodes and creating Closure-compatible constructs.
199
200
```typescript { .api }
201
function hasModifierFlag(declaration: ts.Declaration, flag: ts.ModifierFlags): boolean;
202
function isAmbient(node: ts.Node): boolean;
203
function isDtsFileName(fileName: string): boolean;
204
function getIdentifierText(identifier: ts.Identifier): string;
205
function symbolIsValue(tc: ts.TypeChecker, sym: ts.Symbol): boolean;
206
```
207
208
[Transformer Utilities](./transformer-utilities.md)
209
210
### Path Utilities
211
212
Utilities for path manipulation and normalization, providing cross-platform path handling for module resolution and file system operations.
213
214
```typescript { .api }
215
function isAbsolute(path: string): boolean;
216
function join(p1: string, p2: string): string;
217
function dirname(path: string): string;
218
function relative(base: string, rel: string): string;
219
function normalize(path: string): string;
220
```
221
222
[Path Utilities](./path-utilities.md)
223
224
## Types
225
226
```typescript { .api }
227
interface EmitResult extends ts.EmitResult {
228
modulesManifest: ModulesManifest;
229
externs: { [moduleId: string]: string };
230
tsMigrationExportsShimFiles: Map<string, string>;
231
}
232
233
interface EmitTransformers {
234
beforeTs?: ts.CustomTransformers['before'];
235
afterTs?: ts.CustomTransformers['after'];
236
afterDeclarations?: ts.CustomTransformers['afterDeclarations'];
237
}
238
239
interface AnnotatorHost {
240
logWarning?: (warning: ts.Diagnostic) => void;
241
pathToModuleName(context: string, importPath: string): string;
242
untyped?: boolean;
243
typeBlackListPaths?: Set<string>;
244
unknownTypesPaths?: Set<string>;
245
convertIndexImportShorthand?: boolean;
246
provideExternalModuleDtsNamespace?: boolean;
247
moduleResolutionHost: ts.ModuleResolutionHost;
248
options: ts.CompilerOptions;
249
}
250
251
class ModulesManifest {
252
addManifest(other: ModulesManifest): void;
253
addModule(fileName: string, module: string): void;
254
addReferencedModule(fileName: string, resolvedModule: string): void;
255
getFileNameFromModule(module: string): string;
256
getReferencedModules(fileName: string): string[];
257
get modules(): string[];
258
get fileNames(): string[];
259
}
260
261
interface Tag {
262
tagName: string;
263
parameterName?: string;
264
type?: string;
265
optional?: boolean;
266
restParam?: boolean;
267
}
268
```