3

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?

tscpp
  • 1,298
  • 2
  • 12
  • 35
  • 1
    Are you using a [project wide configuration in the root folder or a file-relative one](https://babeljs.io/docs/en/config-files)? – Oluwafemi Sule Jun 26 '20 at 07:29
  • Could you add some more details about what type of transformation you are expecting to see which is not occurring? :) – JuanCaicedo Jun 26 '20 at 16:02
  • Also what are the contents of `src/script.js`? At first I thought it was the node file that you posted, but it seems like that is how you are executing babel? – JuanCaicedo Jun 26 '20 at 16:06
  • In the new update of the post I've included more details and contents (IO). Using a project-wide configuration in the root folder didn't work. – tscpp Jun 27 '20 at 08:08

2 Answers2

1

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
Rain.To
  • 504
  • 2
  • 7
  • It doesn't meet my requirements, e.g. babel-node doesn't support glob as input of file. – tscpp Jun 27 '20 at 08:11
-1

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
);
  • The babel transform with node worked, but that's not it. I want to have babel run a command, not a javascript file. – tscpp Jun 27 '20 at 07:52