当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript core.transform函数代码示例

本文整理汇总了TypeScript中@babel/core.transform函数的典型用法代码示例。如果您正苦于以下问题:TypeScript transform函数的具体用法?TypeScript transform怎么用?TypeScript transform使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了transform函数的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: main

async function main(): Promise<void> {
  console.log(`Compiling React codebase:`);
  const reactFiles = await loadProjectFiles("./example-runner/example-repos/react/packages");
  console.time("Sucrase");
  for (const {code, path} of reactFiles) {
    if (path.endsWith(".ts")) {
      continue;
    }
    sucrase.transform(code, {
      transforms: ["jsx", "imports", "flow"],
      filePath: path,
    });
  }
  console.timeEnd("Sucrase");

  console.time("Babel");
  for (const {code, path} of reactFiles) {
    if (path.endsWith(".ts")) {
      continue;
    }
    babel.transform(code, {
      presets: ["@babel/preset-react", "@babel/preset-flow"],
      plugins: [
        "@babel/plugin-transform-modules-commonjs",
        "@babel/plugin-proposal-class-properties",
        "@babel/plugin-proposal-object-rest-spread",
      ],
    });
  }
  console.timeEnd("Babel");
}
开发者ID:alangpierce,项目名称:sucrase,代码行数:31,代码来源:benchmark-react.ts

示例2: test

  test('does not transform non-meta property', () => {
    const input = stripIndent(`
      console.log(foo.import.meta);
    `);

    const expected = stripIndent(`
      console.log(foo.import.meta);
    `);
    const result =
        babelCore.transform(input, {plugins: [rewriteImportMeta]}).code;
    assert.equal(result.trim(), expected.trim());
  });
开发者ID:MehdiRaash,项目名称:tools,代码行数:12,代码来源:babel-plugin-import-meta_test.ts

示例3: test

  test('transforms import()', () => {
    const input = stripIndent(`
      const dep1 = import('dep1');
    `);

    const expected = stripIndent(`
      const dep1 = import("./node_modules/dep1/index.js");
    `);
    const result =
        babelCore.transform(input, {plugins: [resolveBareSpecifiersTransform]})
            .code;
    assert.equal(result.trim(), expected.trim());
  });
开发者ID:MehdiRaash,项目名称:tools,代码行数:13,代码来源:babel-plugin-bare-specifiers_test.ts

示例4: test

  test('transforms import()', () => {
    const input = stripIndent(`
      const foo = import('./foo.js');
    `);

    const expected = stripIndent(`
      import * as _require from 'require';
      const foo = new Promise((res, rej) => _require.default(['./foo.js'], res, rej));
    `);
    const result =
        babelCore.transform(input, {plugins: [dynamicImportAmd]}).code;
    assert.equal(result.trim(), expected.trim());
  });
开发者ID:MehdiRaash,项目名称:tools,代码行数:13,代码来源:babel-plugin-dynamic-import-amd_test.ts

示例5: test

  test('transforms import.meta with specified base', () => {
    const input = stripIndent(`
      console.log(import.meta);
    `);

    const expected = stripIndent(`
      console.log({
        url: new URL("./bar.js", 'http://foo.com/').toString()
      });
    `);
    const plugin = rewriteImportMeta('./bar.js', 'http://foo.com/');
    const result = babelCore.transform(input, {plugins: [plugin]}).code;
    assert.equal(result.trim(), expected.trim());
  });
开发者ID:Polymer,项目名称:polymer-build,代码行数:14,代码来源:babel-plugin-import-meta_test.ts

示例6:

import * as babel from "@babel/core";

const options: babel.TransformOptions = {
    ast: true,
    sourceMaps: true
};

babel.transform("code();", options, (err, result) => {
    const { code, map, ast } = result!;
});

const transformSyncResult = babel.transformSync("code();", options);
if (transformSyncResult) {
    const { code, map, ast } = transformSyncResult;
}

babel.transformFile("filename.js", options, (err, result) => {
    const { code, map, ast } = result!;
});

babel.transformFileSync("filename.js", options)!.code;

const sourceCode = "if (true) return;";
const parsedAst = babel.parse(sourceCode, options);

babel.transformFromAst(parsedAst!, sourceCode, options, (err, result) => {
    const { code, map, ast } = result!;
});

const transformFromAstSyncResult = babel.transformFromAstSync(parsedAst!, sourceCode, options);
const { code, map, ast } = transformFromAstSyncResult!;
开发者ID:AlexGalays,项目名称:DefinitelyTyped,代码行数:31,代码来源:babel__core-tests.ts

示例7: babel7Transform

export default function transform<T> (options: Options): TransformResult {
  const code = options.isTyped
    ? babel7Transform(options.code, {
      parserOpts: {
        sourceType: 'module',
        plugins: [
          'typescript',
          'classProperties',
          'jsx',
          'trailingFunctionCommas',
          'asyncFunctions',
          'exponentiationOperator',
          'asyncGenerators',
          'objectRestSpread',
          'decorators'
        ] as any[]
      },
      plugins: [
        '@babel/plugin-transform-typescript'
      ]
    }).code
    : options.code
  setting.sourceCode = code
  // babel-traverse 无法生成 Hub
  // 导致 Path#getSource|buildCodeFrameError 都无法直接使用
  // 原因大概是 babylon.parse 没有生成 File 实例导致 scope 和 path 原型上都没有 `file`
  // 将来升级到 babel@7 可以直接用 parse 而不是 transform
  const ast = parse(code, {
    parserOpts: {
      sourceType: 'module',
      plugins: [
        'typescript',
        'classProperties',
        'jsx',
        'flow',
        'flowComment',
        'trailingFunctionCommas',
        'asyncFunctions',
        'exponentiationOperator',
        'asyncGenerators',
        'objectRestSpread',
        'decorators'
      ] as any[]
    }
  }).ast as t.File
  // transformFromAst(ast, code)
  let result
  const componentSourceMap = new Map<string, string[]>()
  const imageSource = new Set<string>()
  let mainClass!: NodePath<t.ClassDeclaration>
  let storeName!: string
  let renderMethod!: NodePath<t.ClassMethod>
  traverse(ast, {
    ClassDeclaration (path) {
      mainClass = path
    },
    ClassMethod (path) {
      if (t.isIdentifier(path.node.key) && path.node.key.name === 'render') {
        renderMethod = path
      }
    },
    AwaitExpression (path) {
      const isAsyncImported = ast.program.body.some(statement => {
        return t.isImportDeclaration(statement) && statement.source.value === ASYNC_PACKAGE_NAME
      })
      if (!isAsyncImported) {
        ast.program.body.unshift(
          t.importDeclaration([], t.stringLiteral(ASYNC_PACKAGE_NAME))
        )
      }
    },
    JSXOpeningElement (path) {
      const { name } = path.node.name as t.JSXIdentifier
      if (name === 'Provider') {
        const modules = path.scope.getAllBindings('module')
        const providerBinding = Object.values(modules).some((m: Binding) => m.identifier.name === 'Provider')
        if (providerBinding) {
          path.node.name = t.jSXIdentifier('View')
          const store = path.node.attributes.find(attr => attr.name.name === 'store')
          if (store && t.isJSXExpressionContainer(store.value) && t.isIdentifier(store.value.expression)) {
            storeName = store.value.expression.name
          }
          path.node.attributes = []
        }
      }

      if (IMAGE_COMPONENTS.has(name)) {
        for (const attr of path.node.attributes) {
          if (
            t.isIdentifier(attr) &&
            attr.name.name === 'src'
          ) {
            if (t.isStringLiteral(attr.value)) {
              imageSource.add(attr.value.value)
            } else if (t.isJSXExpressionContainer(attr.value)) {
              if (t.isStringLiteral(attr.value.expression)) {
                imageSource.add(attr.value.expression.value)
              }
            }
          }
//.........这里部分代码省略.........
开发者ID:teachat8,项目名称:taro,代码行数:101,代码来源:index.ts

示例8: tryParseCjs

function tryParseCjs (source) {
  const requires = new Set();
  let hasProcess, hasBuffer;
  const { ast } = babel.transform(source, {
    ast: true,
    babelrc: false,
    babelrcRoots: false,
    configFile: false,
    highlightCode: false,
    compact: false,
    sourceType: 'script',
    parserOpts: {
      allowReturnOutsideFunction: true,
      plugins: stage3Syntax
    },
    plugins: [({ types: t }) => {
      function resolvePartialWildcardString (node, lastIsWildcard) {
        if (t.isStringLiteral(node))
          return node.value;
        if (t.isTemplateLiteral(node)) {
          let str = '';
          for (let i = 0; i < node.quasis.length; i++) {
            const quasiStr = node.quasis[i].value.cooked;
            if (quasiStr.length) {
              str += quasiStr;
              lastIsWildcard = false;
            }
            const nextNode = node.expressions[i];
            if (nextNode) {
              const nextStr = resolvePartialWildcardString(nextNode, lastIsWildcard);
              if (nextStr.length) {
                lastIsWildcard = nextStr.endsWith('*');
                str += nextStr;
              }
            }
          }
          return str;
        }
        if (t.isBinaryExpression(node) && node.operator === '+') {
          const leftResolved = resolvePartialWildcardString(node.left, lastIsWildcard);
          if (leftResolved.length)
            lastIsWildcard = leftResolved.endsWith('*');
          const rightResolved = resolvePartialWildcardString(node.right, lastIsWildcard);
          return leftResolved + rightResolved;
        }
        return lastIsWildcard ? '' : '*';
      }

      return {
        visitor: {
          ReferencedIdentifier (path) {
            const identifierName = path.node.name;
            if (!hasProcess && identifierName === 'process' && !path.scope.hasBinding('process'))
              hasProcess = true;
            if (!hasBuffer && identifierName === 'Buffer' && !path.scope.hasBinding('Buffer'))
              hasBuffer = true;
          },
          CallExpression (path) {
            if (t.isIdentifier(path.node.callee, { name: 'require' })) {
              const req = resolvePartialWildcardString(path.node.arguments[0], false);
              if (req !== '*')
                requires.add(req);
            }
            else if (t.isMemberExpression(path.node.callee) &&
                     t.isIdentifier(path.node.callee.object, { name: 'require' }) &&
                     t.isIdentifier(path.node.callee.property, { name: 'resolve' })) {
              const req = resolvePartialWildcardString(path.node.arguments[0], false);
              if (req.indexOf('*') !== -1)
                requires.add(req);
            }
          }
        }
      };
    }]
  });
  if (hasProcess && !requires.has('process'))
    requires.add('process');
  if (hasBuffer && !requires.has('buffer'))
    requires.add('buffer');
  return { ast, requires };
}
开发者ID:jspm,项目名称:jspm-cli,代码行数:81,代码来源:dew-worker.ts

示例9: 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 doBabel = 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.minify) {
    doBabel = true;
    // Minify last, so push first.
    presets.push(babelPresetMinify);
  }
  if (options.compileToEs5) {
    doBabel = true;
    presets.push(babelPresetEs2015NoModules);
    plugins.push(...babelTransformPlugins);
  }
  if (options.moduleResolution === 'node') {
    if (!options.filePath) {
      throw new Error(
          'Cannot perform node module resolution without filePath.');
    }
    doBabel = true;
    plugins.push(resolveBareSpecifiers(
        options.filePath,
        !!options.isComponentRequest,
        options.packageName,
        options.componentDir,
        options.rootDir));
  }
  if (options.transformImportMeta === true ||
      (options.transformImportMeta === undefined &&
       options.transformModulesToAmd === true)) {
    if (!options.filePath) {
      throw new Error('Cannot perform importMeta transform without filePath.');
    }
    if (!options.rootDir) {
      throw new Error('Cannot perform importMeta transform without rootDir.');
    }
    doBabel = true;
    let relativeURL = relative(options.rootDir, options.filePath);
    if (isWindows()) {
      // normalize path separators to URL format
      relativeURL = relativeURL.replace(/\\/g, '/');
    }
    plugins.push(rewriteImportMeta(relativeURL));
  }
  if (options.transformModulesToAmd) {
    if (options.transformImportMeta === false) {
      throw new Error(
          'Cannot use transformModulesToAmd without transformImportMeta.');
    }
    doBabel = true;
    plugins.push(...babelTransformModulesAmd);
  }

  if (doBabel) {
    try {
      js = babelCore.transform(js, {presets, plugins}).code!;
    } 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 (options.transformModulesToAmd && options.moduleScriptIdx !== undefined) {
    const generatedModule = generateModuleName(options.moduleScriptIdx);
    const previousGeneratedModule = options.moduleScriptIdx === 0 ?
        undefined :
        generateModuleName(options.moduleScriptIdx - 1);
    const depStr = previousGeneratedModule === undefined ?
        '' :
        `'${previousGeneratedModule}', `;
    // The AMD Babel plugin will produce a `define` call with no name argument,
    // since it assumes its name corresponds to its file name. This is an inline
    // script, though, and we need a handle to it for chaining, so insert a name
    // argument.
    js = js.replace('define([', `define('${generatedModule}', [${depStr}`);
  }

  js = replaceTemplateObjectNames(js);

  return js;
}
开发者ID:Polymer,项目名称:polymer-build,代码行数:96,代码来源:js-transform.ts

示例10:

import * as babel from "@babel/core";

const options: babel.TransformOptions = {
    ast: true,
    sourceMaps: true
};

babel.transform("code();", options, (err, result) => {
    const { code, map, ast } = result!;
    const { body } = ast!.program;
});

const transformSyncResult = babel.transformSync("code();", options);
if (transformSyncResult) {
    const { code, map, ast } = transformSyncResult;
    const { body } = ast!.program;
}

babel.transformFile("filename.js", options, (err, result) => {
    const { code, map, ast } = result!;
    const { body } = ast!.program;
});

babel.transformFileSync("filename.js", options)!.code;

const sourceCode = "if (true) return;";
const parsedAst = babel.parse(sourceCode, options);

babel.transformFromAst(parsedAst!, sourceCode, options, (err, result) => {
    const { code, map, ast } = result!;
    const { body } = ast!.program;
开发者ID:CNBoland,项目名称:DefinitelyTyped,代码行数:31,代码来源:babel__core-tests.ts

示例11: babelTransform

 parse: function (source: any) {
   return babelTransform(source, {
     code: false,
     ast: true,
     sourceMap: false,
     presets: [babelPresetEnv]
   }).ast;
 }
开发者ID:benjamn,项目名称:recast,代码行数:8,代码来源:babel.ts


注:本文中的@babel/core.transform函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。