當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript babylon.parse函數代碼示例

本文整理匯總了TypeScript中babylon.parse函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript parse函數的具體用法?TypeScript parse怎麽用?TypeScript parse使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了parse函數的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: test

  test('returns events from a comment', () => {
    const node = parse(`
        class Foo {
          /**
           * This is an event
           *
           * @event event-name
           * @param {Event} event
           */
           myMethod() { }

           /**
            * @event descriptionless-event
            */
           anotherMethod() { }
        }`);
    const events = [...getEventComments(node).values()];
    const eventMatches = events.map((ev) => ({
                                      description: ev.description,
                                      name: ev.name,
                                      params: ev.params,
                                      warnings: ev.warnings
                                    }));

    assert.deepEqual(eventMatches, [
      {
        description: 'descriptionless-event',
        name: 'descriptionless-event',
        params: [],
        warnings: []
      },
      {
        description: 'This is an event',
        name: 'event-name',
        params: [{desc: '', name: 'event', type: 'Event'}],
        warnings: []
      }
    ]);
  });
開發者ID:MehdiRaash,項目名稱:tools,代碼行數:39,代碼來源:esutil_test.ts

示例2: run

  static run(content: string): StageResult {
    let log = logger(this.name);
    log(content);

    let editor = new MagicString(content);
    let ast = parse(content, {
      sourceType: 'module',
      plugins: BABYLON_PLUGINS,
      allowReturnOutsideFunction: true,
      tokens: true
    } as any); // tslint:disable-line no-any
    let config = buildConfig(content, ast);

    asi(config);

    config.insertions.forEach(({ index, content }: Insertion) => editor.appendLeft(index, content));
    config.removals.forEach(({ start, end }: Removal) => editor.remove(start, end));

    return {
      code: editor.toString(),
      suggestions: []
    };
  }
開發者ID:alangpierce,項目名稱:decaffeinate,代碼行數:23,代碼來源:index.ts

示例3: assert

/// <reference types="babel-types" />
/// <reference types="babel-types" />


// Example from https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#babylon
import * as babylon from "babylon";
declare function assert(expr: boolean): void;

const code = `function square(n) {
  return n * n;
}`;

let node = babylon.parse(code);
assert(node.type === "File");
assert(node.start === 0);
assert(node.end === 38);
assert(node.loc.start > node.loc.end);


babylon.parse(code, {
  sourceType: "module", // default: "script"
  plugins: ["jsx"] // default: []
});
開發者ID:ArtemZag,項目名稱:DefinitelyTyped,代碼行數:23,代碼來源:babylon-tests.ts

示例4:

const parse = (source: string) =>
  babylon.parse(source, {
    sourceType: 'module',
    plugins: ['jsx', 'typescript', 'classProperties', 'objectRestSpread']
  });
開發者ID:OfficeDev,項目名稱:office-ui-fabric-react,代碼行數:5,代碼來源:codepenTransform.ts

示例5: parse

/// <reference types="babylon" />



// Example from https://github.com/babel/babel/tree/master/packages/babel-generator
import {parse} from 'babylon';
import generate from 'babel-generator';

const code = 'class Example {}';
const ast = parse(code);

ast.type;
ast.loc.start;

const output = generate(ast, { /* options */ }, code);


// Example from https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#babel-generator
let result = generate(ast, {
    retainLines: false,
    compact: "auto",
    concise: false,
    quotes: "double",
    // ...
}, code);
result.code;
result.map;
開發者ID:ArtemZag,項目名稱:DefinitelyTyped,代碼行數:27,代碼來源:babel-generator-tests.ts

示例6: Identifier

        }
    }
};

const MyVisitor2: Visitor = {
    Identifier(path) {
        console.log("Visiting: " + path.node.name);
    }
};

// Example from https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#babel-traverse
const code = `function square(n) {
    return n * n;
}`;

const ast = babylon.parse(code);

traverse(ast, {
    enter(path) {
        const node = path.node;
        if (t.isIdentifier(node) && node.name === "n") {
            node.name = "x";
        }
    }
});

// Examples from https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#writing-your-first-babel-plugin

const v1: Visitor = {
    BinaryExpression(path) {
        if (t.isIdentifier(path.node.left)) {
開發者ID:AbraaoAlves,項目名稱:DefinitelyTyped,代碼行數:31,代碼來源:babel-traverse-tests.ts

示例7: jsTransform

export function jsTransform(js: string, options: JsTransformOptions): string {
  // Even with no transform plugins, parsing and serializing with Babel will
  // make some minor formatting changes to the code. Skip Babel altogether
  // if we have no meaningful changes to make.
  let doBabelTransform = false;

  // Note that Babel plugins run in this order:
  // 1) plugins, first to last
  // 2) presets, last to first
  const plugins = [...babelSyntaxPlugins];
  const presets = [];

  if (options.externalHelpers) {
    plugins.push(babelExternalHelpersPlugin);
  }
  if (options.minify) {
    doBabelTransform = true;
    // Minify last, so push first.
    presets.push(babelPresetMinify);
  }
  if (options.compile === true || options.compile === 'es5') {
    doBabelTransform = true;
    plugins.push(...babelTransformEs2015);
    plugins.push(...babelTransformEs2016);
    plugins.push(...babelTransformEs2017);
    plugins.push(...babelTransformEs2018);
  } else if (options.compile === 'es2015') {
    doBabelTransform = true;
    plugins.push(...babelTransformEs2016);
    plugins.push(...babelTransformEs2017);
    plugins.push(...babelTransformEs2018);
  } else if (options.compile === 'es2016') {
    doBabelTransform = true;
    plugins.push(...babelTransformEs2017);
    plugins.push(...babelTransformEs2018);
  } else if (options.compile === 'es2017') {
    doBabelTransform = true;
    plugins.push(...babelTransformEs2018);
  }
  if (options.moduleResolution === 'node') {
    if (!options.filePath) {
      throw new Error(
          'Cannot perform node module resolution without filePath.');
    }
    doBabelTransform = true;
    plugins.push(resolveBareSpecifiers(
        options.filePath,
        !!options.isComponentRequest,
        options.packageName,
        options.componentDir,
        options.rootDir));
  }

  // When the AMD option is "auto", these options will change based on whether
  // we have a module or not (unless they are already definitely true).
  let transformModulesToAmd = options.transformModulesToAmd;
  if (transformModulesToAmd === true) {
    doBabelTransform = true;
  }

  const maybeDoBabelTransform =
      doBabelTransform || transformModulesToAmd === 'auto';

  if (maybeDoBabelTransform) {
    let ast;
    try {
      ast = babylon.parse(js, {
        // TODO(aomarks) Remove any when typings are updated for babylon 7.
        // tslint:disable-next-line: no-any
        sourceType: transformModulesToAmd === 'auto' ? 'unambiguous' as any :
                                                       'module',
        plugins: [
          'asyncGenerators',
          'dynamicImport',
          // tslint:disable-next-line: no-any
          'importMeta' as any,
          'objectRestSpread',
        ],
      });
    } catch (e) {
      if (options.softSyntaxError && e.constructor.name === 'SyntaxError') {
        console.error(
            'ERROR [polymer-build]: failed to parse JavaScript' +
                (options.filePath ? ` (${options.filePath}):` : ':'),
            e);
        return js;
      } else {
        throw e;
      }
    }

    if (transformModulesToAmd === 'auto' &&
        ast.program.sourceType === 'module') {
      transformModulesToAmd = true;
    }

    if (transformModulesToAmd) {
      doBabelTransform = true;
      plugins.push(...babelTransformModulesAmd);
    }
//.........這裏部分代碼省略.........
開發者ID:poehlmann,項目名稱:EvaluacionDiferencialDeLaMemoria,代碼行數:101,代碼來源:js-transform.ts

示例8: parseNumber

/**
 * Parses JavaScript source representing a number.
 */
export default function parseNumber(string: string): number {
  let expressionStatement = parse(`(${string})`).program.body[0] as ExpressionStatement;
  let literal = expressionStatement.expression as NumericLiteral;
  return literal.value;
}
開發者ID:alangpierce,項目名稱:decaffeinate-parser,代碼行數:8,代碼來源:parseNumber.ts

示例9: parseRegExp

/**
 * Parses JavaScript source representing a regular expression.
 */
export default function parseRegExp(string: string): { pattern: string, flags?: string } {
  let expressionStatement = parse(`(${string})`).program.body[0] as ExpressionStatement;
  let literal = expressionStatement.expression as RegExpLiteral;
  return literal;
}
開發者ID:alangpierce,項目名稱:decaffeinate-parser,代碼行數:8,代碼來源:parseRegExp.ts


注:本文中的babylon.parse函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。