Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import and convert JS files using Gulp & Babel

Consider the following files:

//foo.js
(function(){
  console.log('working');
})();

//bar.js
import 'foo.js';

Now I'm using gulp to compiled from ES6 to ES5. Here's the relevant task:

gulp.task('build-js', function() {
  return gulp.src('bar.js')
    .pipe(babel({
      presets: ['es2015']
    }))
    .pipe(gulp.dest('./dist'));
});

My output file looks like this:

'use strict';
require('foo.js');

The isn't the outcome I expected. I want all code to import into the single output file using the ES5 conversion. This way, the single JS file can be loaded in a browser and run correctly. What do I need to do for the desired outcome?

Since bar.js only imports foo.js, the output file should look exactly like foo.js. Also, since foo.js contains only a self executing function, the output file should execute this immediately and log working to the console.

like image 594
CaribouCode Avatar asked Oct 19 '22 11:10

CaribouCode


1 Answers

You should add a 'bundle' task if you want to create a single file for the browser. Take a look at browserify or webpack.

http://browserify.org/ https://webpack.github.io/

You usually need to specify an entry point, and the bundler resolves all the dependencies and creates a single js file.

EDIT:

An example task for gulp, using browserify:

var browserify = require('gulp-browserify');
gulp.task('bundle', function() {
    gulp.src('./dist/bar.js') // entry point
        .pipe(browserify())
        .pipe(gulp.dest('./dist'))
});
like image 199
carlosdubusm Avatar answered Oct 27 '22 10:10

carlosdubusm