javascriptgulpecmascript-6babeljsgulp-babel

Babel does not convert ES6 to JavaScript that is understandable by browsers


I use Gulp as task manager and Babel for convert my ES6 program to a version that is understandable for browsers, not for Node!

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

gulp.task('default', () =>
    gulp.src('src/app.js')
        .pipe(babel({
            presets: ['es2015']
        }))
        .pipe(gulp.dest('dist'))
);

and in src/app.js I have:

import { square, diag } from 'lib';
//Some code here....

But, when I run the gulp, it make a file in dist but it converts import which is in app.js file to require keyword that is not understandable for browsers... I thought bable will merge imported files in src/app.js to one file in dist

How can I convert my library code to be supported by browsers using Babel?


Solution

  • Basicly Babeljs converts your ES6 to ES5, Imagine you have an ES6 code:

    const secret = ({ msg = 'es 6 hey!'} = {}) => () => msg;
    

    The above code is in ES6, and Babeljs will help you to convert it to ES5:

    'use strict';
    
    var secret = function secret() {
      var _ref = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
    
      var _ref$msg = _ref.msg;
      var msg = _ref$msg === undefined ? 'es 6 hey!' : _ref$msg;
      return function () {
        return msg;
      };
    };
    

    And require is not a [current] JavaScript standard, you need a 3rd-party library that also have a function named require, libraries like requirejs, browserify, etc.

    Even, if you have an ES6 program that includes any export or import keywords when you are working with Babili (online ES6 to ES5 converter) that will notify you that those converted keywords are not supported by browsers:

    require is not supported in the browser, you need a commonjs environment such as node.js/io.js, browserify/webpack etc

    Online demo