How to use the transform function from @babel/core

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

@babel/core.transform is a function in Babel that transforms ECMAScript 2015+ code into a backwards compatible version of JavaScript.

9
10
11
12
13
14
15
16
17
18
names.split(',').forEach(function (name) {
  hash[name] = true
})

function addvm (code) {
  var r = babel.transform(code, {
    plugins: [function ({ types: t }) {
      return {
        visitor: {
          Identifier: function (path, state) {
fork icon925
star icon42
watch icon6

+ 5 other calls in file

7
8
9
10
11
12
13
14
15
16

const importedDefinitionsCache = new Map();

// react-docgen does not understand typescript annotations
function stripTypeScript(filename, ast) {
  return babelCore.transform(babelCore.transformFromAst(ast).code, {
    filename: filename,
    babelrc: false,
    presets: ['@babel/typescript'],
    plugins: ['@babel/plugin-syntax-dynamic-import'],
fork icon755
star icon0
watch icon2

+ 5 other calls in file

How does @babel/core.transform work?

@babel/core.transform is a function provided by the Babel compiler that takes in a JavaScript code string, along with a configuration object specifying the desired transformations, and returns an object containing the transformed code, as well as any associated metadata. When called, the function first parses the input code string into an abstract syntax tree (AST), which represents the structure of the code in a format that can be more easily manipulated. The configuration object is then used to traverse and modify the AST as needed, typically using a set of plugins or presets that define the specific transformations to apply. Finally, the transformed code is generated by printing the modified AST back out to a string representation.

117
118
119
120
121
122
123
124
125
126
  ]);
}

babelConfig.filename = path;

src = babel.transform(src, babelConfig).code;

return {
  code: src,
};
fork icon150
star icon383
watch icon39

+ 5 other calls in file

179
180
181
182
183
184
185
186
187
      };
    },
  ],
});
const {transform} = require('@babel/core');
const jsCode = await transform(jsxCode, {
  plugins: ['@babel/plugin-transform-modules-commonjs'],
  presets: ['@babel/preset-react'],
}).code;
fork icon317
star icon458
watch icon32

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const babel = require("@babel/core");

const code = `
const square = (x) => x * x;
console.log(square(5));
`;

const options = {
  presets: ["@babel/preset-env"],
};

const result = babel.transform(code, options);

console.log(result.code);

In this example, @babel/core.transform is used to transform some ES6 code into compatible ES5 code using the @babel/preset-env preset. The transformed code is then printed to the console.

406
407
408
409
410
411
412
413
414
415
    config.presets.push(extraPreset);
  }
  if (this.__privateMangling == "unreadable") {
    config.blacklist = ["spec.functionName"];
  }
  result = babelCore.transform(src, config);
} catch (ex) {
  qx.tool.compiler.Console.log(ex);
  t.addMarker("compiler.syntaxError", ex.loc, ex.message);
  t.__fatalCompileError = true;
fork icon257
star icon756
watch icon76

+ 14 other calls in file

1
2
3
4
5
6
7
8
9
10
const babel = require('@babel/core')

useReducer({
  WxsImportExpression(node) {
    let { content, dist } = node.body
    content = babel.transform(content, {
      plugins: [
        [
          ({ types: t }) => ({
            visitor: {
fork icon139
star icon0
watch icon24

+ 11 other calls in file

98
99
100
101
102
103
104
105
106
107
### via [Babel API](https://babeljs.io/docs/usage/api/)

```javascript
var babel = require('@babel/core');
var jsCode = fs.readFileSync('/path/to/test/some_test.js');
var transformed = babel.transform(jsCode, {
    presets: [...],
    plugins: ['babel-plugin-espower']
});
console.log(transformed.code);
fork icon6
star icon94
watch icon12

+ 2 other calls in file

444
445
446
447
448
449
450
451
452
453

// Remove client-exclude marked code.
source = source.replace(/\/\* CEXCLUDE \*\/[\s\S.]*?\* CEXCLUDE \*\//g, '');

// Return final code.
return babel.transform(source, {
	ast: true,
	compact: true,
	minified: true,
	comments: false,
fork icon4
star icon7
watch icon4

+ 8 other calls in file

10
11
12
13
14
15
16
17
18
19
20
const {wrap} = require('jest-snapshot-serializer-raw');
const freshPlugin = require('react-refresh/babel');


function transform(input, options = {}) {
  return wrap(
    babel.transform(input, {
      babelrc: false,
      configFile: false,
      envName: options.envName,
      plugins: [
fork icon0
star icon3
watch icon1

93
94
95
96
97
98
99
100
101
102
  runTests(executeCommon, testCommon);
});

describe('with typescript syntax', () => {
  runTests(function(source) {
    const typescriptSource = babel.transform(source, {
      babelrc: false,
      configFile: false,
      presets: ['@babel/react'],
      plugins: [
fork icon0
star icon3
watch icon1

217
218
219
220
221
222
223
224
225
226
const { transform } = require('@babel/core');
const fs = require('fs');
// 读取需要转换的js字符串
const before = fs.readFileSync('./before.js', 'utf8');
// 使用babel-core的transform的API和插件进行字符串 -> AST转化
const res = transform(`${before}`, {
  plugins: [require('./my-plugin')]
});

// 存在after.js删除
fork icon0
star icon2
watch icon1

+ 5 other calls in file

135
136
137
138
139
140
141
142
143
144
 * @param {string} filename
 */
function minifyAndWriteJs(js, filename) {
  const minified =
      // @ts-ignore
      babelCore.transform(js, {presets: [babelPresetMinify]}).code;
  const libDir = path.join(__dirname, '..', 'lib');
  try {
    fs.mkdirSync(libDir);
  } catch (e) { /* don't care */ }
fork icon204
star icon1
watch icon2

144
145
146
147
148
149
150
151
152
];

gulp.task('gen-babel-helpers', () => {
  const helpersCode = babelCore.buildExternalHelpers(babelHelperWhitelist);
  const minified =
      babelCore.transform(helpersCode, {presets: [babelPresetMinify]}).code;
  fs.mkdirpSync('./lib/');
  fs.writeFileSync('./lib/babel-helpers.min.js', minified, {encoding: 'utf-8'});
});
fork icon40
star icon0
watch icon0

+ 3 other calls in file

18
19
20
21
22
23
24
25
26
27
/**
 * @param {string} js
 * @param {string} filename
 */
function minifyAndWriteJs(js, filename) {
  const output = babelCore.transform(js, {
    presets: [babelPresetMinify]
  }).code;
  const vendor = path.join(__dirname, '..', 'src', 'vendor');
  try {
fork icon21
star icon0
watch icon2

39
40
41
42
43
44
45
46
47
48
const importDepend = cache.getDepend(dirPath)
// if (isRoot && importDepend) {
//   return importDepend
// }
const context = fs.readFileSync(dirPath,'utf-8')
const tranform = babel.transform(context)
const ast = babel.parseSync(tranform.code)
const nameTemplate = babel.template(`window.%%name%% = %%name%%`)
const reactDOM = babel.template(`ReactDOM.render(React.createElement(%%name%%,{},{}),document.getElementById('root'))`)
traverse(ast,{
fork icon3
star icon0
watch icon1

+ 5 other calls in file

66
67
68
69
70
71
72
73
74
75
    }).join("\n\n") : 
    jetpack.find(jsPath, { matching : "*.js" }).map( fileName => {
        return jetpack.read(fileName);
    }).join("\n\n");

js = Babel.transform(js, babelOptions).code;

Terser.minify(js, terserOptions).then(result => {
    if (result.error) {
        console.error(result.error);
fork icon2
star icon0
watch icon1

215
216
217
218
219
220
221
222
223
224

```
const babel = require('@babel/core')
const code = `const fn = (a, b) => a + b`
// babel 有 transform 方法会帮我们自动遍历,使用相应的预设或者插件转换相应的代码
const r = babel.transform(code, {
  presets: ['@babel/preset-env'],
})
console.log(r.code)
// 打印结果如下
fork icon2
star icon0
watch icon1

+ 23 other calls in file

91
92
93
94
95
96
97
98
99
100
101
102
103


const extractFromFile = async filename => {
  try {
    const code = await readFile(filename);


    const output = await transform(code, { filename, presets, plugins });
    const messages = get(output, 'metadata.react-intl.messages', []);


    for (const message of messages) {
      for (const locale of appLocales) {
fork icon1
star icon1
watch icon0

4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
}


function transformDynamicClass(staticClass, clsBinding) {
    if (staticClass === void 0) staticClass = ""


    var result = babel.transform("!" + clsBinding, { plugins: [transformObjectToTernaryOperator] })
    // 先实现功能,再优化代码
    // https://github.com/babel/babel/issues/7138
    var cls = prettier
        .format(result.code.replace("use strict'!",'').replace('"use strict";',''), { semi: false, singleQuote: true, parser:'babel' })//fixed by xxxxxx
fork icon0
star icon0
watch icon1

+ 13 other calls in file

738
739
740
741
742
743
744
745
746
747
if (typeIsJS) {
	const originalContents = minifyHTMLInJS(String(contents));
	await fs.writeFile(`${fullPath}.source`, originalContents);
	const filenameIndex = path.lastIndexOf("/") + 1;
	const filename = path.slice(filenameIndex);
	const compiled = babel.transform(originalContents, {
		ast: false,
		comments: false,
		compact: true,
		filename,
fork icon0
star icon0
watch icon1