How to use the @babel/template.ast function in @babel/template

To help you get started, we’ve selected a few @babel/template examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github uber / react-view / src / code-generator.ts View on Github external
case PropTypes.Enum:
      return t.identifier(String(value));
    case PropTypes.Date:
      return t.newExpression(
        t.identifier('Date'),
        value ? [t.stringLiteral(String(value))] : []
      );
    case PropTypes.Ref:
      return null;
    case PropTypes.Object:
      return template.ast(`${value}`, {plugins: ['jsx']}) as any;
    case PropTypes.Array:
    case PropTypes.Number:
    case PropTypes.Function:
    case PropTypes.ReactNode:
      const output = (template.ast(String(value), {plugins: ['jsx']}) as any)
        .expression;
      // we never expect that user would input a variable as the value
      // treat it as a string instead
      if (output.type === 'Identifier') {
        return t.stringLiteral(output.name);
      }
      return output;
    case PropTypes.Custom:
      if (!customProps[name] || !customProps[name].generate) {
        console.error(`Missing customProps.${name}.generate definition.`);
      }
      return customProps[name].generate(value);
  }
};
github ttag-org / babel-plugin-ttag / src / utils.js View on Github external
export const validateAndFormatMsgid = (msgid, exprNames) => {
    const msgidAST = tpl.ast(strToQuasi(msgid));
    const msgidExprs = new Set(msgidAST.expression.expressions.map(ast2Str));
    exprNames.forEach((exprName) => {
        if (!msgidExprs.has(exprName)) {
            throw new NoExpressionError(`Expression '${exprName}' is not found in the localized string '${msgid}'.`);
        }
    });

    // need to regenerate template to fix spaces between in ${}
    // because translator can accidentally add extra space or remove
    return generate(msgidAST).code.replace(/;$/, '');
};
github uber / baseweb / documentation-site / components / yard / code-generator.ts View on Github external
import * as t from '@babel/types';

// forked prettier on a diet
//@ts-ignore
import prettier from '@miksu/prettier/lib/standalone';
//@ts-ignore
import parsers from '@miksu/prettier/lib/language-js/parser-babylon';

type TJsxChild =
  | t.JSXText
  | t.JSXExpressionContainer
  | t.JSXSpreadChild
  | t.JSXElement
  | t.JSXFragment;

const reactImport = template.ast(`import * as React from 'react';`);

export const getAstPropsArray = (props: {[key: string]: TProp}) => {
  return Object.entries(props).map(([name, prop]) => {
    const {value, stateful, defaultValue} = prop;
    if (stateful)
      return t.jsxAttribute(
        t.jsxIdentifier(name),
        t.jsxExpressionContainer(t.identifier(name)),
      );
    // When the `defaultValue` is set and `value` is the same as the `defaultValue`
    // we don't add it to the list of props.
    // It handles boolean props where `defaultValue` set to true,
    // and enum props that have a `defaultValue` set to be displayed
    // in the yard correctly (checked checkboxes and selected default value in radio groups)
    // and not rendered in the component's props.
    if (
github evenchange4 / graphql.macro / src / utils / compileWithFragment.js View on Github external
// @flow
import gqlTag from 'graphql-tag';
import serialize from 'babel-literal-to-ast';
import template from '@babel/template';

/**
 * TODO: Reduce runtime to improve performance
 * ref: https://github.com/gajus/babel-plugin-graphql-tag/blob/35edbae44990bf20be2de7139dc0ce5843f70bff/src/index.js#L25
 */
const uniqueFn = template.ast(`
  (acc, definition) =>
    definition.kind === 'FragmentDefinition' &&
    acc.find(
      curDef =>
        curDef.kind === 'FragmentDefinition' &&
        curDef.name.value === definition.name.value,
    )
      ? acc
      : acc.concat(definition)
`);

/**
 * ref: https://github.com/leoasis/graphql-tag.macro
 */
export default function compileWithFragment(
  referencePath: Object,
github blocks / blocks / packages / blocks-ui / src / babel-plugins / insert-before.js View on Github external
export default (_, { elementId } = {}) => {
  const ast = template.ast(`<h1>hello!</h1>`, {
    plugins: ['jsx']
  })

  return {
    visitor: {
      JSXOpeningElement(path) {
        const id = path.node.attributes.find(
          node =&gt; node &amp;&amp; node.name &amp;&amp; node.name.name === uuidName
        )

        if (!id || id.value.value !== elementId) {
          return
        }

        path.parentPath.insertBefore(ast.expression)
      }
github blocks / blocks / packages / blocks-ui / src / babel-plugins / insert-after.js View on Github external
export default (_, { elementId } = {}) =&gt; {
  const ast = template.ast(`<h1>hello!</h1>`, {
    plugins: ['jsx']
  })

  return {
    visitor: {
      JSXOpeningElement(path) {
        const id = path.node.attributes.find(
          node =&gt; node &amp;&amp; node.name &amp;&amp; node.name.name === uuidName
        )

        if (!id || id.value.value !== elementId) {
          return
        }

        path.parentPath.insertAfter(ast.expression)
      }
github blocks / blocks / packages / blocks-ui / src / babel-plugins / inject-blocks-root.js View on Github external
import template from '@babel/template'

const root = template.ast(
  `
  const BLOCKS_Root = ({ children }) =&gt; {
    return (
      
        {(provided, snapshot) =&gt; {
          const allProps = Object.assign(
            provided.droppableProps,
            {
              ref: provided.innerRef,
              style: {
                minHeight: '100%'
              },
            }
          )

          return React.createElement(
github blocks / blocks / packages / builder / babel-plugin-text-edit.js View on Github external
JSXText(path) {
        const openingElement = path.parentPath.node.openingElement
        if (openingElement.name.name === 'BLOCKS_Text') {
          return
        }

        const { expression: wrapper } = template.ast(
          `
          
        `,
          {
            plugins: ['jsx']
          }
        )

        //wrapper.children = [path.node]
        //path.replaceWith(wrapper)
      }
    }
github hsiaosiyuan0 / jlua / src / js / code.js View on Github external
static prepareRuntime() {
    const ast = template.ast(`
  const __jlua__ =  require("jlua/lib/js/runtime");
`);
    return Array.isArray(ast) ? ast : [ast];
  }
github ttag-org / babel-plugin-ttag / src / extractors / ngettext.js View on Github external
ARGS: t.arrayExpression(args.map((l) => {
            let quasis;
            let expressions;
            if (context.isNumberedExpressions()) {
                const transNode = tpl.ast(strToQuasi(l));
                quasis = transNode.expression.quasis;
                expressions = transNode.expression.expressions
                    .map(({ value }) => value)
                    .map((i) => msgidTag.quasi.expressions[i]);
            } else {
                const transNode = tpl.ast(validateAndFormatMsgid(l, exprs));
                quasis = transNode.expression.quasis;
                expressions = transNode.expression.expressions;
            }
            return t.templateLiteral(quasis, expressions);
        })),
    });