Skip to content

Commit e70d11c

Browse files
authored
Merge pull request #703 from huafu/refac-jest-hoisting
[beta] Use the proper way of mutating a node in a transformer
2 parents c5a5b7a + 2e56c30 commit e70d11c

3 files changed

Lines changed: 12 additions & 14 deletions

File tree

src/transformers/README.md

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,9 @@ See https://dev.doctorevidence.com/how-to-write-a-typescript-transform-plugin-fc
55
## Boilerplate
66

77
```ts
8-
import {
9-
TransformationContext,
10-
SourceFile,
11-
Visitor,
12-
Transformer,
13-
} from 'typescript';
14-
import { ConfigSet } from '../config-set'
8+
import { SourceFile, TransformationContext, Transformer, Visitor } from 'typescript'
9+
10+
import { ConfigSet } from '../config/config-set'
1511

1612
// this is a unique identifier for your transformer
1713
export const name = 'my-transformer'
@@ -26,7 +22,7 @@ export function factory(cs: ConfigSet) {
2622
// new nodes if we want to leave the node as is, and
2723
// continue searching through child nodes:
2824
return ts.visitEachChild(node, visitor, ctx)
29-
};
25+
}
3026
return visitor
3127
}
3228
// we return the factory expected in CustomTransformers
Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -98,14 +98,17 @@ export function factory(cs: ConfigSet) {
9898
enter()
9999

100100
// visit each child
101-
const resultNode = ts.visitEachChild(node, visitor, ctx)
101+
let resultNode = ts.visitEachChild(node, visitor, ctx)
102102

103103
// check if we have something to hoist in this level
104104
if (hoisted[level] && hoisted[level].length) {
105105
// re-order children so that hoisted ones appear first
106-
// this is actually the main work of this transformer
107-
const block = resultNode as Block
108-
block.statements = ts.createNodeArray([...hoisted[level], ...block.statements])
106+
// this is actually the main job of this transformer
107+
const hoistedStmts = hoisted[level]
108+
const otherStmts = (resultNode as Block).statements.filter(s => !hoistedStmts.includes(s))
109+
const newNode = ts.getMutableClone(resultNode) as Block
110+
newNode.statements = ts.createNodeArray([...hoistedStmts, ...otherStmts])
111+
resultNode = newNode
109112
}
110113

111114
// exit the level
@@ -114,7 +117,6 @@ export function factory(cs: ConfigSet) {
114117
if (shouldHoistNode(resultNode)) {
115118
// hoist into current level
116119
hoist(resultNode as Statement)
117-
return
118120
}
119121

120122
// finsally returns the currently visited node

src/transformers/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { AstTransformerDesc } from '../types'
22

3-
import * as hoisting from './hoisting'
3+
import * as hoisting from './hoist-jest'
44

55
export const internals: AstTransformerDesc[] = [hoisting]

0 commit comments

Comments
 (0)