How to use the transformFileAsync function from @babel/core

Find comprehensive JavaScript @babel/core.transformFileAsync code examples handpicked from public code repositorys.

In Babel, the @babel/core.transformFileAsync function is used to asynchronously transform the contents of a file using a specified set of Babel plugins and options.

28
29
30
31
32
33
34
35
36
37

  return `const {\n${imports}\n} = Spectacle;\n\n${htmImport}`;
};

const getSrcContent = async (src) => {
  let { code } = await transformFileAsync(src, {
    babelrc: false,
    configFile: false,
    plugins: ['babel-plugin-transform-jsx-to-htm']
  });
fork icon734
star icon0
watch icon153

113
114
115
116
117
118
119
120
121
122
        transformJSXImportsToJS(path)
      }
    },
  },
}] : undefined
const { code, map } = await babel.transformFileAsync(file, { sourceMaps: true, plugins })
const [{ default: chalk }] = await Promise.all([
  import('chalk'),
  writeFile(libFile, code),
  writeFile(`${libFile}.map`, JSON.stringify(map)),
fork icon0
star icon1
watch icon0

+ 7 other calls in file

How does @babel/core.transformFileAsync work?

@babel/core.transformFileAsync is an asynchronous function in the Babel library that is used to transform the contents of a file using a specified set of Babel plugins and options.

When @babel/core.transformFileAsync is called with a file path and a set of options as input, it performs the following operations:

  • It reads the contents of the file at the specified path.
  • It applies a set of Babel plugins and options to the file contents, transforming the code as specified by the plugins and options.
  • It returns a Promise that resolves to an object containing the transformed code as a string, as well as other information about the transformation process such as source maps and AST.

By using @babel/core.transformFileAsync, developers can transform the code in files asynchronously using Babel, which can be useful for dealing with I/O operations that may take some time to complete. This function can be used in build processes or other automated tasks where code transformation is required. Note that @babel/core.transformFileAsync may not work as expected with certain types of code or plugins, so it is important to test thoroughly before using it in production code.

37
38
39
40
41
42
43
44
45
46
.then(files => {
  Promise.all(
    files.map(filename => {
      // todo 可以匹配一些规则,直接返回

      return transformFileAsync(filename, {
        plugins: [
          // 装饰器插件
          ['@babel/plugin-proposal-decorators', { legacy: true }],
          scan,
fork icon459
star icon0
watch icon0

18
19
20
21
22
23
24
25
26
27
async run(from, options) {
  const to = seen.get(from)
  const fromDirectory = from.replace(path.basename(from), '')
  const toDirectory = to.replace(path.basename(to), '')
  logger.debug(from + ' => ' + to)
  const { code, map, ast } = await babel.transformFileAsync(from, {
    cwd: options.cwd,
    babelrc: false,
    presets: [require.resolve('@repay/babel-preset')],
    sourceMaps: true,
fork icon1
star icon0
watch icon0

+ 3 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const fs = require("fs");
const babel = require("@babel/core");

// Reading the contents of a file asynchronously
fs.readFile("input.js", "utf8", (err, inputCode) => {
  if (err) throw err;

  // Applying Babel transformations to the code asynchronously
  babel
    .transformFileAsync(inputCode, {
      presets: ["@babel/preset-env"],
    })
    .then((result) => {
      // Writing the transformed code to a file asynchronously
      fs.writeFile("output.js", result.code, "utf8", (err) => {
        if (err) throw err;
        console.log("Transformation complete!");
      });
    });
});

In this example, we're using @babel/core.transformFileAsync to transform the contents of a file named "input.js" asynchronously using the @babel/preset-env preset. The transformed code is then written to a file named "output.js" asynchronously. Note that @babel/core.transformFileAsync returns a Promise that resolves to an object with information about the transformation, including the transformed code as a string, source maps, and AST. These values can be used for advanced use cases, such as debugging or customizing the Babel transformation process.

43
44
45
46
47
48
49
50
51
52
53
54
function compileCode(config, packagePath, dir, path) {
  const sourcePath = resolve(packagePath, path)


  console.log('compile at:', sourcePath)


  transformFileAsync(sourcePath, config)
    .then((output) => {
      let outputPath = getOutputPath(packagePath, dir, 'src', path)
      outputPath = replaceExtname(outputPath, '.js')
      safeWriteFile(outputPath, output.code)
fork icon0
star icon0
watch icon1

+ 4 other calls in file

69
70
71
72
73
74
75
76
77

debug(CompilationLifecycles['closured-pre-babel'], file);
/** @type {?babel.TransformOptions} */
const babelOptions = babel.loadOptions({caller: {name: 'post-closure'}});
const {code, map: babelMap} =
  (await babel.transformFileAsync(file, babelOptions ?? undefined)) || {};
if (!code || !babelMap) {
  throw new Error(`Error transforming contents of ${file}`);
}
fork icon0
star icon0
watch icon0

100
101
102
103
104
105
106
107
108
109
110


function transpileES6Files() {
  console.log('Transpiling ES6 files to ES5 to ' + DIST_DIR + '...');
  let srcFile = JS_SRC_DIR + 'main.js';
  let destFile = DIST_DIR + 'js/main.js'; // Overrides the existing un-transpiled file
  return babel.transformFileAsync(srcFile)
    .then(result => {
      return new Promise((resolve, reject) => {
        fs.writeFile(destFile, result.code, (error, data) => {
          resolve(true);
fork icon0
star icon0
watch icon0

+ 3 other calls in file