Search code examples
babeljsbabel-clibabel-core

Can not transform code with babel transform with config file


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?


Solution

  • 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