Can not transform code with babel transform with config file

1.2k views Asked by At

This is the config file:

{
    "presets": [
        "@babel/preset-env"
    ],
    "plugins": [
        "@babel/plugin-transform-modules-commonjs"
    ]
}

This is the command:

npx babel src/* --out-dir build

The CLI output is

src/script.js -> build\src\script.js

The output script file is identical to the input script file.


This is the node.js file:

const babel = require('@babel/core');
const fs = require('fs');

fs.writeFileSync(
    'build/index.js',
    babel.transformFileSync(
        'src/index.js',
        {
            plugins: ["@babel/plugin-transform-modules-commonjs"]
        }
    ).code
);

The output script file's content is what is expected.


I used this as input:

const test = 0;
export default { test };

This is the output from the CLI command shown above.

const test = 0;
export default { test };

This is the output from the NodeJS file shown above (which is my expected output from the CLI).

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var test = 0;
var _default = {
  test: test
};
exports["default"] = _default;

Q: Can you you babel CLI to transform code?

2

There are 2 answers

1
Rain.To On BEST ANSWER

We have used babel-node in scenario where we want to transpile. https://babeljs.io/docs/en/next/babel-node.html

npx babel-node src/* --out-dir build
1
B''H Bi'ezras -- Boruch Hashem On

Not sure why transform, which is an async function, is being used inside a synchroous, blocking execution. Instead use transformSync and .code

fs.writeFileSync(
    'build/script.js',
    babel.transformSync(
        fs.readFileSync('src/script.js').toString('utf8'),
        {
            plugins: ["@babel/plugin-transform-modules-commonjs"]
        }
    ).code
);

Or even more, you can use transformFileSync:

fs.writeFileSync(
    'build/script.js',
    babel.transformFileSync(
        'src/script.js',
        {
            plugins: ["@babel/plugin-transform-modules-commonjs"]
        }
    ).code
);