Skip to content

Commit bcdb8f0

Browse files
author
Michael Dougall
committed
chore: adds tips and tricks for composing transformers
1 parent d059bb6 commit bcdb8f0

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

translations/en/transformer-handbook.md

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,9 @@ This document covers how to write a [Typescript](https://typescriptlang.org/) [T
6262
- [Following module imports](#following-module-imports)
6363
- [Transforming jsx](#transforming-jsx)
6464
- [Determining the file pragma](#determining-the-file-pragma)
65-
- [Throwing a syntax error to ease the developer experience](#throwing-a-syntax-error-to-ease-the-developer-experience)
65+
- [Tips & tricks](#tips--tricks)
66+
- [Composing transformers](#composing-transformers)
67+
- [Throwing a syntax error to ease the developer experience](#throwing-a-syntax-error-to-ease-the-developer-experience)
6668
- [Testing](#testing)
6769
- [`ts-transformer-testing-library`](#ts-transformer-testing-library)
6870
- [Known bugs](#known-bugs)
@@ -1243,7 +1245,32 @@ The source file below would cause `'a jsx pragma was found using the factory "js
12431245
Currently as of 29/12/2019 `pragmas` is not on the typings for `sourceFile` -
12441246
so you'll have to cast it to `any` to gain access to it.
12451247

1246-
## Throwing a syntax error to ease the developer experience
1248+
## Tips & tricks
1249+
1250+
### Composing transformers
1251+
1252+
If you're like me sometimes you want to split your big transformer up into small more maintainable pieces.
1253+
Well luckily with a bit of coding elbow grease we can achieve this:
1254+
1255+
```ts
1256+
const transformers = [...];
1257+
1258+
function transformer(
1259+
program: ts.Program,
1260+
): ts.TransformerFactory<ts.SourceFile> {
1261+
return context => {
1262+
const initializedTransformers = transformers.map(transformer => transformer(program)(context));
1263+
1264+
return sourceFile => {
1265+
return initializedTransformers.reduce((source, transformer) => {
1266+
return transformer(source);
1267+
}, sourceFile);
1268+
};
1269+
};
1270+
}
1271+
```
1272+
1273+
### Throwing a syntax error to ease the developer experience
12471274

12481275
> **TODO** - Is this possible like it is in Babel?
12491276
> Or we use a [language service plugin](https://github.com/Microsoft/TypeScript/wiki/Writing-a-Language-Service-Plugin)?

0 commit comments

Comments
 (0)