ffxsam ffxsam - 5 months ago 10
Javascript Question

How to remove comments from transpiled code

I've been looking around for some

.babelrc
option to remove comments from the transpiled code, but I haven't had any luck. I tried this:

{
"comments": false
}


as well as

{
"options": {
"comments": false
}
}


and neither works. I'm out of ideas, and I was unable to find any decent documentation anywhere.

Answer

Where are you running babel from? Gulp?

Check that you have the .babelrc file in the same or a parent directory of the files beign transpiled

From babeljs.io:

Babel will look for a .babelrc in the current directory of the file being transpiled. If one does not exist, it will travel up the directory tree until it finds either a .babelrc, or a package.json with a "babel": {} hash within.

I have a project with this structure:

  • dist
    • index.js
  • .babelrc
  • index.js
  • gulpfile.js
  • node_modules
    • ...

The relevant task in gulpfile.js

gulp.task('babel', () => {
    return gulp.src('index.js')
        .pipe(babel({
            presets: ['es2015']
        }))
        .pipe(gulp.dest('./dist/'));
});

Contents of .babelrc

{
    "comments": false
}

The comments are being succesfully removed.

Also check if you're not setting the comments option to true in your gulpfile, for example.

EDIT

It does look like a problem with babel CLI ignoring the comments in .babelrc , a workaround is to use the --no-comments option.

In your package.json

"build": "babel ./index.js --out-dir ./dist/index.js --no-comments"

To know all the options of babel-cli

./node_modules/.bin/babel -h