From 352aa44c0ae255a06446286a68ba64eeff101a00 Mon Sep 17 00:00:00 2001 From: Marvin Hagemeister Date: Sat, 15 Jul 2017 12:27:54 +0200 Subject: [PATCH] Add react helpers to babel-types --- types/babel-types/babel-types-tests.ts | 27 ++++++++++++++++++++++++++ types/babel-types/index.d.ts | 13 +++++++++++-- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/types/babel-types/babel-types-tests.ts b/types/babel-types/babel-types-tests.ts index 5974a64885..394603ab31 100644 --- a/types/babel-types/babel-types-tests.ts +++ b/types/babel-types/babel-types-tests.ts @@ -29,3 +29,30 @@ t.assertBinaryExpression(ast); t.assertBinaryExpression(ast, { operator: "*" }); var exp: t.Expression = t.nullLiteral(); + +// React examples: + +// https://github.com/babel/babel/blob/4e50b2d9d9c376cee7a2cbf56553fe5b982ea53c/packages/babel-plugin-transform-react-inline-elements/src/index.js#L61 +traverse(ast, { + JSXElement(path, file) { + const { node } = path; + const open = node.openingElement; + + // init + const type = open.name; + + let newType: t.StringLiteral; + if (t.isJSXIdentifier(type) && t.react.isCompatTag(type.name)) { + newType = t.stringLiteral(type.name); + } + + const args: any[] = []; + if (node.children.length) { + const children = t.react.buildChildren(node); + args.push( + t.unaryExpression("void", t.numericLiteral(0), true), + ...children, + ); + } + } +}); diff --git a/types/babel-types/index.d.ts b/types/babel-types/index.d.ts index 77ea8b54de..c3f77b559f 100644 --- a/types/babel-types/index.d.ts +++ b/types/babel-types/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for babel-types v6.7 +// Type definitions for babel-types v6.25 // Project: https://github.com/babel/babel/tree/master/packages/babel-types -// Definitions by: Troy Gerwien , Sam Baxter +// Definitions by: Troy Gerwien +// Sam Baxter +// Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export interface Comment { @@ -1226,6 +1228,13 @@ export function isUser(node: Object, opts?: Object): boolean; export function isGenerated(node: Object, opts?: Object): boolean; export function isPure(node: Object, opts?: Object): boolean; +// React specific +interface ReactHelpers { + isCompatTag(tagName?: string): boolean; + buildChildren(node: Object): Object[]; +} +export const react: ReactHelpers; + export function assertArrayExpression(node: Object, opts?: Object): void; export function assertAssignmentExpression(node: Object, opts?: Object): void; export function assertBinaryExpression(node: Object, opts?: Object): void;