當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。