@babel/core#transformSync TypeScript Examples

The following examples show how to use @babel/core#transformSync. 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: utils.ts    From design-systems-cli with MIT License 7 votes vote down vote up
transform = (source: string, filename = '/test.js') => {
  const results = transformSync(source, {
    filename,
    plugins: [[plugin, { scope: 'cgds' }]],
    configFile: false
  });

  if (results && results.code) {
    return results.code;
  }

  throw Error('Something went wrong.');
}
Example #2
Source File: utils.ts    From design-systems-cli with MIT License 7 votes vote down vote up
transform = (source: string, filename = 'test/test.js') => {
  const results = transformSync(source, {
    filename,
    plugins: [[plugin, { scope: 'cgds', use: 'test' }]],
    configFile: false,
  });

  if (results && results.code) {
    return results.code;
  }

  throw Error('Something went wrong.');
}
Example #3
Source File: index.test.ts    From vanilla-extract with MIT License 6 votes vote down vote up
transform = (
  source: string,
  options: Options = {},
  filename = './dir/mockFilename.css.ts',
) => {
  const result = transformSync(source, {
    filename,
    cwd: __dirname,
    plugins: [[plugin, options]],
    configFile: false,
  });

  if (!result) {
    throw new Error('No result');
  }

  return result.code;
}
Example #4
Source File: analyze.ts    From codehawk-cli with MIT License 6 votes vote down vote up
transpileFileSource = (
  sourceCode: string,
  fileExtension: string,
  isTypescript: boolean,
  enableFlow: boolean
): string => {
  let contents = sourceCode

  if (isTypescript) {
    const transformed = transformSync(contents, {
      plugins: [
        [
          '@babel/plugin-transform-typescript',
          {
            isTSX: fileExtension === '.tsx',
          },
        ],
      ],
    })
    contents = transformed.code || ''
  } else {
    // Assume no other static type systems exist
    // Stripping flow types should be safe, even if it's not strictly flow
    contents = enableFlow
      ? flowRemoveTypes(contents, { pretty: true }).toString()
      : contents
  }

  return contents
}
Example #5
Source File: plugin.test.ts    From i18n-helper with MIT License 6 votes vote down vote up
transformCode = (code: string) => {
  const result = transformSync(code, {
    plugins: [['@babel/plugin-syntax-typescript', { isTSX: true }], plugin],
    // compact: true,
    retainLines: true,
  });

  return result;
}
Example #6
Source File: onlineDemoBuildPlugin.ts    From react-dev-inspector with MIT License 6 votes vote down vote up
onlineDemoBuildPlugin = (): Plugin => ({
  name: 'online-demo-build-plugin',
  enforce: 'pre',
  apply: 'build',

  transform(code, id) {
    if (!/\.(t|j)sx$/.test(id) || id.includes('node_modules')) {
      return code
    }

    const result = transformSync(code, {
      filename: id,
      babelrc: false,
      configFile: false,
      compact: false,
      parserOpts: {
        sourceType: 'module',
        plugins: [
          'typescript',
          'jsx',
        ],
      },
      plugins: [
        'react-dev-inspector/plugins/babel',
      ],
    })

    return result?.code
  },
})
Example #7
Source File: babel-plugin.test.ts    From react-dev-inspector with MIT License 6 votes vote down vote up
// https://github.com/babel-utils/babel-plugin-tester#options
pluginTester({
  title: 'inspector babel plugin test',
  plugin: InspectorBabelPlugin,
  pluginName: 'InspectorBabelPlugin',
  pluginOptions: <InspectorPluginOptions>{
    cwd: `${cwd}/examples/umi3/src`,
  },

  babelOptions,

  tests: globby
    .sync(`${assetsBaseDir}/layouts/**/*.tsx`)
    .map((filePath) => path.relative(assetsBaseDir, filePath))
    .map((asset) => ({
      fixture: path.join(cwd, assetsBaseDir, asset),
      outputFixture: path.join(cwd, fixturesBaseDir, asset),
    })),
  formatResult: (code: string) => transformSync(code, babelOptions)?.code ?? '',
})
Example #8
Source File: macro-assertions.ts    From typecheck.macro with MIT License 4 votes vote down vote up
export function getUserFuncArg(
  path: NodePath<t.Node>,
  functionName: string,
  fileText: string,
  filename: string
): UserFunctions {
  if (!t.isObjectExpression(path)) {
    throw new MacroError(
      `${functionName}'s second argument must be an object expression`
    );
  }
  const props = path.get("properties");
  assertArray(props);

  const getChild = (
    key: string
  ): Array<NodePath<t.ObjectMethod | t.ObjectProperty | t.SpreadElement>> => {
    const prop = find(
      props,
      (x) => t.isObjectProperty(x) && get(x, "node.key.name", null) === key
    );
    if (prop !== undefined) {
      const value = prop.get("value");
      assertSingular(value);
      if (!t.isObjectExpression(value)) {
        throw new MacroError(
          `key: "${key}" of ${functionName}'s second argument must be a object expression`
        );
      }
      return value.get("properties") as ReturnType<typeof getChild>;
    }
    return [];
  };
  const constraintMap: Constraints = new Map();
  const forbiddenVarNames = new Set<string>();
  const transformers: UserFunctions = {
    [transformerKeys.c]: constraintMap,
    forbiddenVarNames,
  };
  const refiners = getChild(transformerKeys.c);
  for (const prop of refiners) {
    if (!t.isObjectProperty(prop)) {
      throw new MacroError(
        `${functionName}'s second argument must be an object expression composed of key-value pairs, where the keys are statically known (not computed)`
      );
    }
    const typeName = get(prop, "node.key.name", null);
    if (typeName === null) {
      throw new MacroError(
        `Failed to get key name when parsing 2nd parameter of ${functionName}`
      );
    }
    if (typeof typeName !== "string" && typeof typeName !== "number") {
      throw new MacroError(
        `Expected ${JSON.stringify(typeName)} to be string or number`
      );
    }
    const valuePath = prop.get("value");
    assertSingular(valuePath);
    const refinementValueError = new MacroError(
      `The values of the refinement object in the 2nd parameter of ${functionName} must be strings or function declarations`
    );
    if (
      t.isArrowFunctionExpression(valuePath) ||
      t.isFunctionExpression(valuePath)
    ) {
      const { start, end } = valuePath.node;
      if (start === null || end === null) {
        throw new MacroError(
          `Failed to extract function text from 2nd parameter of ${functionName}`
        );
      }
      valuePath.traverse({
        Identifier(path, _) {
          forbiddenVarNames.add(path.node.name);
        },
      });
      const functionText = "(" + fileText.slice(start, end) + ")";
      // compile the function in order to remove type annotations
      const result = transformSync(functionText, { filename });
      let code = result?.code;
      if (code === null || code === undefined) {
        throw new MacroError(
          `Failed to compile function pass as value of 2nd parameter of ${functionName}`
        );
      }
      code = code.replace(/^"use strict";\n*/, "");
      // parenthesis will be kept around function expressions and not around arrow functions
      // arrow functions will be ended with a semi-colon
      if (code.slice(-1) === ";") code = code.slice(0, -1);
      code = "(" + code + ")";
      constraintMap.set(typeName, { value: code, type: "function" });
    } else {
      throw refinementValueError;
    }
  }
  return transformers;
}