How convert .jsx to .js with Gulp and Babel?

2020-02-27 05:46发布

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?

5条回答
狗以群分
2楼-- · 2020-02-27 05:58

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"));
});
查看更多
Juvenile、少年°
3楼-- · 2020-02-27 06:00

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/"));
});
查看更多
Animai°情兽
4楼-- · 2020-02-27 06:05
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.

查看更多
兄弟一词,经得起流年.
5楼-- · 2020-02-27 06:16

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

查看更多
疯言疯语
6楼-- · 2020-02-27 06:17

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"));
});
查看更多
登录 后发表回答