How to use @babel/generator - 10 common examples

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 erukiti / ast-book-sample / chapter2 / try-babel-generator.js View on Github external
const generate = require('@babel/generator').default

const ast = {
  type: 'ExpressionStatement',
  expression: {
    type: 'BinaryExpression', 
    operator: '+',
    left: {type: 'NumericLiteral', value: 1},
    right: {type: 'NumericLiteral', value: 2}
  }
}

const {code, map} = generate(ast)
console.log(code)
// 1 + 2;
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 ismail-codar / fidan / packages / babel-plugin-fidan-jsx / build / ast.js View on Github external
const errorReport = (e, path, file) => {
    const nodeCode = generator_1.default(path.node).code;
    console.log("FILE: ", file.filename);
    console.log("PART: ", nodeCode);
    console.error("ERROR: ", e);
    debugger;
};
function setAttr(elem, name, value) {
github cube-js / cube.js / packages / cubejs-schema-compiler / compiler / DataSchemaCompiler.js View on Github external
transpileFile(file, errorsReport) {
    try {
      const ast = parse(
        file.content,
        {
          sourceFilename: file.fileName,
          sourceType: 'module',
          plugins: ['objectRestSpread']
        },
      );
      this.transpilers.forEach((t) => babelTraverse(ast, t.traverseObject()));
      const content = babelGenerator(ast, {}, file.content).code;
      return Object.assign({}, file, { content });
    } catch (e) {
      if (e.toString().indexOf('SyntaxError') !== -1) {
        const line = file.content.split('\n')[e.loc.line - 1];
        const spaces = Array(e.loc.column).fill(' ').join('');
        errorsReport.error(`Syntax error during '${file.fileName}' parsing: ${e.message}:\n${line}\n${spaces}^`);
      } else {
        errorsReport.error(e);
      }
    }
    return undefined;
  }
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}.`);
}

@babel/generator

Turns an AST into code.

MIT
Latest version published 23 days ago

Package Health Score

95 / 100
Full package analysis

Similar packages