-
Notifications
You must be signed in to change notification settings - Fork 170
/
transform-react-jsx-source.ts
41 lines (39 loc) · 1.46 KB
/
transform-react-jsx-source.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { ts } from '../deps.ts'
/**
* TypeScript AST Transformer that adds source file and line number to JSX elements.
*
* @link https://github.com/dropbox/ts-transform-react-jsx-source
*/
export default function transformReactJsxSource(sf: ts.SourceFile, node: ts.Node): ts.VisitResult<ts.Node> {
if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) {
const fileNameAttr = ts.createPropertyAssignment(
'fileName',
ts.createStringLiteral(sf.fileName)
)
const lineNumberAttr = ts.createPropertyAssignment(
'lineNumber',
ts.createNumericLiteral((sf.getLineAndCharacterOfPosition(node.pos).line + 1).toString())
)
const sourceJsxAttr = ts.createJsxAttribute(
ts.createIdentifier('__source'),
ts.createJsxExpression(undefined, ts.createObjectLiteral([fileNameAttr, lineNumberAttr]))
)
const jsxAttributes = ts.createJsxAttributes([
...node.attributes.properties,
sourceJsxAttr
])
if (ts.isJsxSelfClosingElement(node)) {
return ts.createJsxSelfClosingElement(
node.tagName,
node.typeArguments,
jsxAttributes
)
} else if (ts.isJsxOpeningElement(node)) {
return ts.createJsxOpeningElement(
node.tagName,
node.typeArguments,
jsxAttributes
)
}
}
}