Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Browserify and Babel gulp tasks

I want to use both Browserify and Babel with my JavaScript. For this I created a gulp task

gulp.task('babel', function() {
    return gulp.src('_babel/*.js')
        .pipe(browserify({ insertGlobals : true }))
        .pipe(babel({ presets: ['es2015'] }))
        .pipe(gulp.dest('_dev/js'));
});

Unfortunately, when I want to use import within my code, I am getting an error:

ParseError: 'import' and 'export' may only appear at the top level

My main js file is very simple:

import 'directives/toggleClass';

I'm guessing that it is because of Babel (and it's use strict addition), but what can I do?

like image 422
Tomek Buszewski Avatar asked Dec 14 '15 21:12

Tomek Buszewski


1 Answers

Babel maintains an official transform for Browserify called babelify and it should be used wherever possible if using babel and browserify.

Drop the use of babel directly and place babelify as a transform plugin for browserify. There are many ways to configure browserify but specifying config in your package.json would probably be easiest.

"browserify": { 
  "transform": [["babelify", { "presets": ["es2015"] }]]
}

Your gulp task will then be simplified

gulp.task('babel', function() {
    return gulp.src('_babel/*.js')
        .pipe(browserify({ insertGlobals : true }))
        .pipe(gulp.dest('_dev/js'));
});

Browserify also exposes methods to do this programmatically so you will be able to configure the bundler from inside your gulp task (dropping the package config, although using the package is perfectly fine for this), check their documentation and experiment, I've done it before but its been a long time since I used gulp (using gulp here is just a complication you dont need, but I expect you are using it elsewhere in your build pipeline where it might be more helpful).

like image 189
Matt Styles Avatar answered Nov 05 '22 07:11

Matt Styles