18

I need to convert all /src/.jsx files to /src/.js

Before I used gulp-react:

var react = require('gulp-react');

gulp.task('jsx', function () {
  return gulp.src('src/jsx/*.jsx')
   .pipe(react())
   .pipe(gulp.dest('src/js/'));
});

It works but not without some small mistakes. When I use Babel website (https://babeljs.io/repl/) all converts right. Could you help me. How can I set gulp to convert .JSX files?

  • Seems like the documentation on Babel's website covers this: http://babeljs.io/docs/setup/#gulp And there are tons of resources already explaining how to use `gulp-rename`. – loganfsmyth Oct 20 '15 at 18:31
  • gulp.task('jsx', function () { return gulp.src('src/jsx/*.jsx') .pipe(babel()) .pipe(gulp.dest('src/js/')); }); –  Oct 20 '15 at 18:34
  • I'm not sure what you're trying to say with that comment. Yep, that'll compile. Then you can rename with `gulp-rename`. – loganfsmyth Oct 20 '15 at 19:51

5 Answers5

35

First you need to install these two packages:

npm install gulp-babel babel-plugin-transform-react-jsx

then you can convert like this:

var gulp = require('gulp');
var babel = require('gulp-babel');

gulp.task("babel", function(){
    return gulp.src("src/jsx/*.jsx").
        pipe(babel({
            plugins: ['transform-react-jsx']
        })).
        pipe(gulp.dest("src/js/"));
});
jedierikb
  • 12,752
  • 22
  • 95
  • 166
Navid Farahzadi
  • 681
  • 7
  • 14
6

In order to get displayName automatically inserted on transformation, you need to install gulp-babel and React preset:

npm install --save-dev gulp-babel babel-preset-react

and then in the gulpfile.js:

var gulp = require('gulp');
var babel = require('gulp-babel');

gulp.task("jsx", function(){
    return gulp.src("src/jsx/*.jsx")
        .pipe(babel({
            presets: ["react"]
        }))
        .pipe(gulp.dest("src/js"));
});
itacode
  • 3,721
  • 3
  • 21
  • 23
2
gulp.task('build', ['copy'], function() {
    gulp.src([
            'src/**/*.jsx',
            'src/**/*.js',
            '!./node_modules/**'
        ])
        .pipe(babel({
            presets: ['es2015', 'react']
        }))
        .pipe(gulp.dest('app'));
});

since I am also using ES6.

JFAP
  • 3,617
  • 1
  • 24
  • 25
2

For latest React v16.8.x using Babel 7, use @babel/preset-env and @babel/preset-react modules.

npm i -D @babel/preset-env @babel/preset-react

Then in your gulpfile.js:

var gulp = require('gulp');
var babel = require('gulp-babel');

gulp.task("whatever_task_name_you_prefer", function(){
    return gulp.src("src/jsx/*.jsx")
        .pipe(babel({
            presets: ["@babel/preset-env", @babel/preset-react"]
        }))
        .pipe(gulp.dest("dist"));
});
Waleed93
  • 1,130
  • 2
  • 15
  • 24
0

Yeah using gulp with the package gulp-babel would do the trick.
https://github.com/babel/gulp-babel

Robbie
  • 45
  • 4