Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use both 'gulp-babel' and 'gulp-browserify'

I try to write these code

 gulp.task('script', function() {
  'use strict'
  return gulp.src(['app.js', 'components/**/*.jsx'])
    .pipe(babel())
    .pipe(browserify())
    .pipe(gulp.dest("dist"));
});

but it shows some error:

SyntaxError: 
/Users/Zizy/Programming/learn-react-js/components/CommentBox.jsx:58
    <div className="commentBox">
    ^
ParseError: Unexpected token
    at wrapWithPluginError (/Users/Zizy/Programming/learn-react-js/node_modules/gulp-browserify/index.js:44:10)

It seems that before .pipe(browserify()) the gulp did't transform the jsx code. But if I just remove .pipe(browserify()) I find that did transform, just cannot let babel and browserify work together.

I know maybe I can use like babelify or browserify plugin for babel though, I just want figure out the reason.

like image 614
Zizy Avatar asked Nov 25 '15 18:11

Zizy


1 Answers

gulp-browserify doesn't quite work like that. You don't give it a bunch of buffers to collect and bundle.

You give it one file—the entry file—which it passes into Browserify. Browserify checks to see what other files the entry file references, then loads those files directly from the file system, meaning that you can't modify them with gulp plugins beforehand.

So, really, if we pretend you don't want to use Babel on your source files, your gulpfile should look like this, only passing in the entry file:

 gulp.task('script', function() {
  'use strict'
  return gulp.src('app.js')
    .pipe(browserify())
    .pipe(gulp.dest("dist"));
});

However, note that gulp-browserify is no longer maintained, and this is exactly why. gulp plugins aren't supposed to read directly from the file system. That's why you're supposed to use Browserify (or, in your case, Babelify) directly with vinyl-source-stream as recommended in the gulp recipes. It's more idiomatic and less confusing.

That wraps up my answer to your question, but I'd like to add: if you're using the ES2015 module syntax (and you probably should be), there's a better way to do this. Browserify wraps all your modules separately in a bunch of code to make the programmatic CommonJS API work properly, but ES2015 modules have a declarative syntax, which makes it much easier for tools to operate on them statically. There's a tool called Rollup that takes advantage of this, allowing it to produce bundles that are smaller, faster, and more minfication-friendly than Browserify's.

Here's how you might use it with gulp:

var gulp = require('gulp'),
    rollup = require('rollup-stream'),
    babel = require('gulp-babel'),
    source = require('vinyl-source-stream'),
    buffer = require('vinyl-buffer');

gulp.task('script', function() {
  return rollup({entry: 'app.js'})
    .pipe(source('app.js'))
    .pipe(buffer())
    .pipe(babel())
    .pipe(gulp.dest('dist'));
});
like image 106
Permutator Avatar answered Sep 28 '22 21:09

Permutator