How to use the transformSync function from @babel/core

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

@babel/core.transformSync is a function in the Babel compiler that synchronously transforms input code according to specified Babel plugins and options.

347
348
349
350
351
352
353
354
355
356

### babel7使用方法
- options需要新增参数`filename: 'xxx'`
  ```js
  const { transformSync } = require('@babel/core');
  const { ast } = transformSync(input, {
    // 这里unknown只是示例名,可任意取
    filename: 'unknown',
    plugins: [
      'macros',
fork icon4
star icon16
watch icon2

+ 11 other calls in file

155
156
157
158
159
160
161
162
163
164
: function transform(text) {
    if (options && options.ignore && options.ignore.test(this.filename)) {
      return { code: text };
    }

    return babel.transformSync(text, {
      caller: { name: 'linaria', evaluate: true },
      filename: this.filename,
      presets: [[require.resolve('./index'), options]],
      plugins: [
fork icon410
star icon1
watch icon4

How does @babel/core.transformSync work?

@babel/core.transformSync is a synchronous function provided by the Babel compiler that compiles the given source code using the specified configuration and returns the resulting compiled code and source map in a JavaScript object. It takes in the source code as a string and a configuration object, and it synchronously applies the compilation process to generate the compiled code and source map.

159
160
161
162
163
164
165
166
167
168
            // This will replace dynamic imports with an object that does nothing
            require.resolve('./dynamic-import-noop'),
          ],
        };

        return babel.transformSync(text, defaults);
      };

m.evaluate(
  [
fork icon4
star icon285
watch icon4

+ 5 other calls in file

66
67
68
69
70
71
72
73
74
75
    options.inputSourceMap = context.asset.sourceMap || undefined;
    options.sourceFileName = context.asset.sourceMapPath;
    options.sourceMaps = true;
  }*/

  let result = babel.transformSync(context.asset.source, options);

  context.asset.source = result.code;
  context.asset.sourceMap = result.map;
});
fork icon851
star icon0
watch icon246

+ 5 other calls in file

Ai Example

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

const code = "const foo = (x) => x + 1;";
const options = {
  presets: ["@babel/preset-env"],
};

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

console.log(result.code);

In this example, we first define a code string with some ES6 code that we want to transform. We also define some options that we want to pass to Babel, including a preset to use. Then, we call babel.transformSync with the code and options arguments. This method returns an object with a code property that contains the transformed code. Finally, we log the transformed code to the console.

83
84
85
86
87
88
89
90
91
92
  const runtimeCode = fs.readFileSync(runtimePath, 'utf-8');
  helperSource += `\nexport var regeneratorRuntime;\n\n(function () {${runtimeCode}})();\n`;
}

if (format !== 'es') {
  helperSource = transformSync(helperSource, {
    babelrc: false,
    configFile: false,
    sourceMaps: false,
    plugins: [require.resolve(modulePlugins[format])],
fork icon400
star icon1
watch icon2

+ 3 other calls in file

65
66
67
68
69
70
71
72
73
74
75
76


        }
    }
)();


const transformCode = code => transformSync(code, {
    presets: [babelPresetReact],
    plugins: [
        [babelPluginProposalOptionalChaining, { loose: true }],
        [babelPluginProposalObjectRestSpread, { loose: true }],
fork icon4
star icon27
watch icon4

65
66
67
68
69
70
71
72
73
74
  configFile: false,
  ...defaultBabelConfig,
  ...babelConfig,
};
//  parseSync
const { ast } = babel.transformSync(
  code,
  parserOpts,
);
codeAst = ast;
fork icon430
star icon0
watch icon64

74
75
76
77
78
79
80
81
82
83
    `Already processed ${set.size} files, now is deal with ${target}`
  );
}

const code = fs.readFileSync(target).toString("utf-8");
const nodeHadRemoveTS = babel.transformSync(code, {
  presets: ["@babel/preset-typescript"],
  plugins: [
    [
      "@babel/plugin-proposal-decorators",
fork icon3
star icon19
watch icon2

28
29
30
31
32
33
34
35
36
37
}

let output = cache[filename];

if (!output || output.mtime !== mtime(filename)) {
  output = babel.transformSync(code, {
    ...opts,
    sourceMaps: opts.sourceMaps === undefined ? 'both' : opts.sourceMaps,
    ast: false,
  });
fork icon2
star icon0
watch icon0

87
88
89
90
91
92
93
94
95
96
        }
    }
}

function compile(sourceText, ramdaImport) {
    return transformSync(sourceText, { plugins: [[plugin, { ramdaImport }]] })
        .code
}

module.exports = {
fork icon0
star icon13
watch icon1

280
281
282
283
284
285
286
287
288
289

if (fs.existsSync(targetFilePath)) {
  const fileContents = fs.readFileSync(targetFilePath, 'utf-8');
  try {
    // transpile the file contents to CommonJS
    const { code } = babel.transformSync(fileContents, {
      plugins: [babelTransformEsmToCjs],
      configFile: false,
      babelrc: false,
    });
fork icon754
star icon0
watch icon147

+ 3 other calls in file

25
26
27
28
29
30
31
32
33
34

const source = `
import { LightningElement } from 'lwc';
export default class extends LightningElement {}`;

const { code } = babel.transformSync(source, {
    plugins: [
        [
            lwcPlugin,
            {
fork icon322
star icon0
watch icon88

65
66
67
68
69
70
71
72
73
74
    cache[filename][componentNames[i]] = { [config.name]: hashmap[componentNames[i]].id }
  }
} else {
  const parser = getParser()

  transformSync(content, {
    babelrc: false,
    filename,
    plugins: [
      ...config.syntaxes,
fork icon10
star icon44
watch icon10

44
45
46
47
48
49
50
51
52
53
        load: id => (id !== HELPERS ? null : babel.buildExternalHelpers(null, 'module')),
        transform(code, filename) {
            if (filename === HELPERS) return null;
            // TODO: 优化匹配规则
            if (code.includes(` import(`)) {
                return babel.transformSync(code, { presets: ["@babel/preset-env"] });
            }
        }
    };
};
fork icon20
star icon25
watch icon3

113
114
115
116
117
118
119
120
121
122
    // @ts-ignore
    { isTSX: true, allowExtensions: true, allowDeclareFields: true }
  ])
}

const result = babel.transformSync(code, {
  presets:['@vue/babel-preset-jsx'],
  babelrc: false,
  ast: true,
  plugins: plugins.concat(...babelPlugins),
fork icon0
star icon0
watch icon1

+ 4 other calls in file

20
21
22
23
24
25
26
27
28
29
30
function transformCode(path, source, config = {}) {
  const options = getBabelOptions(path, config);
  const result =
    source === undefined
      ? babel.transformFileSync(path, options)
      : babel.transformSync(source, options);


  if (!result || !result.code) {
    throw new Error(`babel failed to transpile [${path}]`);
  }
fork icon0
star icon0
watch icon1

+ 2 other calls in file

11
12
13
14
15
16
17
18
19
20
let new_fn_template = undefined;
let name = undefined;
let params = undefined;
let body = undefined;

babel.transformSync('function ' + fn_string , {
    plugins : [
        [function(){
            return {
                visitor : {
fork icon0
star icon0
watch icon1

+ 4 other calls in file

164
165
166
167
168
169
170
171
172
173
    }); 
    addChildren(parseFileName , targetFileName);
    return string;
};
 
return babel.transformSync(string , {
    "presets": [
        ["@babel/preset-react", {}],
    ],
    "plugins" : [
fork icon0
star icon0
watch icon1

+ 3 other calls in file

596
597
598
599
600
601
602
603
604
605
	commonJs: opts ? opts.commonJs : false
};

var minified = opts ? opts.minified : false;

var src = babelCore.transformSync(
	code,
	{
		filename: moduleName,
		presets: presetsES8,
fork icon0
star icon0
watch icon2

+ 7 other calls in file

9
10
11
12
13
14
15
16
17
18
19
20
21
"use strict";


const generate = require("@babel/generator").default;


const _require = require("@babel/core"),
  transformSync = _require.transformSync;


function transform(code, plugins, options) {
  const optionsPlugins = plugins.length
    ? plugins.map(plugin => [plugin, options])
fork icon0
star icon0
watch icon1