How to use the @babel/generator function in @babel/generator

To help you get started, we’ve selected a few @babel/generator 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 facebook / prepack / src / serializer / Referentializer.js View on Github external
_createCaptureScopeAccessFunction(referentializationScope: ReferentializationScope): void | BabelNodeStatement {
    // One switch case for one scope.
    const cases = [];
    const serializedScopes = this._getReferentializationState(referentializationScope).serializedScopes;
    type InitializationCase = {|
      scopeIDs: Array,
      value: BabelNodeExpression,
    |};
    const initializationCases: Map = new Map();
    for (const scopeBinding of serializedScopes.values()) {
      if (scopeBinding.initializationValues.length === 0) continue;
      const expr = t.arrayExpression((scopeBinding.initializationValues: any));
      const key = generate(expr, {}, "").code;
      if (!initializationCases.has(key)) {
        initializationCases.set(key, {
          scopeIDs: [scopeBinding.id],
          value: expr,
        });
      } else {
        const ic = initializationCases.get(key);
        invariant(ic);
        ic.scopeIDs.push(scopeBinding.id);
      }
    }
    if (initializationCases.size === 0) return undefined;

    const body = [];
    const selectorParam = t.identifier("__selector");
    const captured = t.identifier("__captured");
github Heigvd / Wegas / wegas-app / src / main / webapp / 2 / src / Editor / Components / FormView / Script / index.tsx View on Github external
if (
        ast.some(
          stmt => !(isExpressionStatement(stmt) || isEmptyStatement(stmt)),
        )
      ) {
        throw Error('Unhandled');
      }
      // ast is (ExpressionStatement|EmptyStatement)[]
      updted = [
        listToLogical((ast as any) as (ExpressionStatement | EmptyStatement)[]),
      ].filter(v => v !== undefined) as Statement[];
    }
    onChange({
      '@class': 'Script',
      language: 'JavaScript',
      content: generate(program(updted)).code,
    });
  }
  const fstStmt = ast[0];
github salesforce / lwc / packages / @lwc / template-compiler / src / metadata / metadata.ts View on Github external
export function getModuleMetadata(element: IRElement): ModuleDependency {
    let properties;
    // Note that we only collect properties and not attributes (such as 'class', 'data-*')
    if (element.props) {
        properties = {};
        for (const [name, value] of Object.entries(element.props)) {
            let returnedType;
            let returnedValue;

            if (value.type === IRAttributeType.Expression) {
                returnedType = 'expression';
                const expression = value.value as TemplateExpression;
                if (babelTypes.isMemberExpression(expression)) {
                    returnedValue = generate(expression).code;
                } else {
                    returnedValue = (expression as TemplateIdentifier).name;
                }
            } else {
                returnedType = 'literal';
                returnedValue = value.value;
            }
            properties[name] = {
                type: returnedType,
                value: returnedValue,
            };
        }
    }

    return {
        moduleName: kebabcaseToCamelcase(element.component),
github Polymer / tools / packages / analyzer / src / javascript / class-scanner.ts View on Github external
function extractPropertyFromExpressionStatement(
    statement: babel.ExpressionStatement,
    document: JavaScriptDocument): ScannedProperty|null {
  let name;
  let astNode;
  let defaultValue;

  if (babel.isAssignmentExpression(statement.expression)) {
    // statements like:
    // /** @public The foo. */
    // this.foo = baz;
    name = getPropertyNameOnThisExpression(statement.expression.left);
    astNode = statement.expression.left;
    defaultValue = generate(statement.expression.right).code;
  } else if (babel.isMemberExpression(statement.expression)) {
    // statements like:
    // /** @public The foo. */
    // this.foo;
    name = getPropertyNameOnThisExpression(statement.expression);
    astNode = statement;
  } else {
    return null;
  }

  if (name === undefined) {
    return null;
  }

  const annotation = getJSDocAnnotationForNode(statement);
  if (!annotation) {
github istanbuljs / istanbuljs / packages / istanbul-lib-instrument / bin / test-render-perf.js View on Github external
const nopt = require('nopt');
const opts = {
    compact: Boolean
};
const parsed = nopt(opts, null, process.argv, 2);
const compact = parsed.compact;

const generateOptions = {
    compact
};

for (let i = 1; i < 15; i += 1) {
    const n = Math.pow(2, i);
    const prog = toProgram(n);
    const start = new Date().getTime();
    const codeMap = generate(prog, generateOptions, '');
    const end = new Date().getTime();
    if (i == 1) {
        console.log('Sample prog:', codeMap.code);
    }
    console.log('Items:', n, ', time:', end - start);
}
github jacobp100 / cssta / compiler / babel / __tests__ / interpolation.ts View on Github external
it("Works with substititions and simple viewport units", () => {
  const ast = babel.parse(`
    const Test = styled(Button)\`
      color: \${red};
      top: 10vw;
      opacity: \${something};
    \`;
  `);
  babel.traverse(ast, {
    TaggedTemplateExpression(path: any) {
      const { tag, quasi: body } = path.node;
      const element = tag.arguments[0];
      buildElement(babel, path, element, body, { jsx: true });
    }
  });
  const { code } = generate(ast);
  expect(code).toMatchInlineSnapshot(`
    "import React from \\"react\\";
    import useWindowDimensions from \\"cssta/runtime/useWindowDimensions\\";
    const Test = React.forwardRef((props, ref) => {
      const {
        width: windowWidth,
        height: windowHeight
      } = useWindowDimensions();
      const baseStyle = {
        color: String(red).trim(),
        top: Number(windowWidth * 0.1),
        opacity: Number(something)
      };
      const style = props.style != null ? [baseStyle, props.style] : baseStyle;
      return <button style="{style}">;
    });"</button>
github facebook / prepack / scripts / instrumentor.js View on Github external
function instrument(inputFilename: string, outputFilename: string) {
  let code = fs.readFileSync(inputFilename, "utf8");
  let ast = parse(code, { inputFilename, sourceType: "script" });
  traverseFast(ast, function(node) {
    if (node.type === "BlockStatement") {
      if (node.loc) ((node: any): BabelNodeBlockStatement).body.unshift(createLogStatement(node.loc));
    }
    return false;
  });
  code = generate(ast, {}, "").code;
  if (!outputFilename) outputFilename = inputFilename + "-instrumented.js";
  fs.writeFileSync(outputFilename, code);
  console.log(`Instrumented source code written to ${outputFilename}.`);
}
github steelbrain / pundle / packages / pundle-loader-css / src / index.js View on Github external
const processModule = await context.resolveSimple('process', file.filePath)
      const ast = template.ast`
        ${file.imports.map(i => `require(${JSON.stringify(i)})`).join('\n')}
        var style = document.createElement('style')
        style.type = 'text/css'
        if (require(${JSON.stringify(processModule)}).env.NODE_ENV === "development" && module.hot && module.hot.dispose) {
          module.hot.dispose(function() {
            style.remove()
          })
        }
        style.textContent = ${JSON.stringify(css)}
        document.head.appendChild(style)
        module.exports = ${JSON.stringify(options.scoped ? randomId : null)}
      `
      const generated = generate(t.program(ast))
      file.addImport(processModule)
      file.sourceContents = Buffer.from(css, 'utf8')

      return {
        contents: generated.code,
        sourceMap: null,
      }
    },
    defaultOptions: {
github Bogdan-Lyashenko / js-code-to-svg-flowchart / src / builder / converters / Harmony.js View on Github external
export const classDeclarationConverter = ({ node }) => {
    return `class ${generate(node.id).code} ${
        node.superClass ? ` extends ${generate(node.superClass).code}` : ''
    }`;
};
github azu / ast-source / src / ASTGenerator.js View on Github external
generateCode(AST) {
        if (this.type === ParserTypes.Esprima) {
            return generate(AST, {
                comment: this.options.comment
            });
        } else if (this.type === ParserTypes.Babylon) {
            return babelGenerate(AST);
        }
    }

@babel/generator

Turns an AST into code.

MIT
Latest version published 18 days ago

Package Health Score

95 / 100
Full package analysis

Similar packages