@babel/core#parse TypeScript Examples

The following examples show how to use @babel/core#parse. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: dump-helpers.ts    From typecheck.macro with MIT License 6 votes vote down vote up
export function replaceWithCode(
  code: string,
  path: NodePath<t.Node>,
  filename: string
): void {
  const ast = parse(code, { filename });
  if (t.isFile(ast)) {
    path.replaceWith(ast.program.body[0]);
  } else {
    throwUnexpectedError(
      `${code} was incorrectly parsed. The AST was: ${JSON.stringify(ast)}`
    );
  }
}
Example #2
Source File: index.ts    From engine with MIT License 5 votes vote down vote up
typeGenerator = (code: string) => {
  const codes = `
    const foo = '123'
    const a: producer = ({
      _bam = bam,
      foo = observe.bam.boo[foo]
    }) => {}
  `;
  const result = parse(
    codes,
    { plugins: ["@babel/plugin-syntax-typescript"] },
    (err, ast) => {
      if (err) {
        throw err;
      }
      traverse(ast, {
        VariableDeclarator: (path) => {
          const id = path.node.id;
          if (
            !(t.isIdentifier(id) || t.isObjectPattern(id)) ||
            !t.isTSTypeAnnotation(id.typeAnnotation) ||
            !t.isTSTypeReference(id.typeAnnotation.typeAnnotation) ||
            !t.isIdentifier(id.typeAnnotation.typeAnnotation.typeName) ||
            !(
              id.typeAnnotation.typeAnnotation.typeName.name ===
                EngineKeywords.VIEW ||
              id.typeAnnotation.typeAnnotation.typeName.name ===
                EngineKeywords.PRODUCER
            )
          ) {
            return;
          }

          if (t.isObjectPattern(id)) {
            return;
          }

          const node = path.node;
          const fn = node.init as t.ArrowFunctionExpression;
          const param = fn.params[0];
          if (param && !t.isObjectPattern(param)) {
            return;
          }
          const parsedParams = paramParser(Babel, param);

          const result = compileParams(parsedParams);
          console.log("ok", JSON.stringify(parsedParams, null, " "));
        },
      });
    }
  );
}