Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Babel es2015 presets doesn't translate Map and Set to es5

I'm using gulp-babel to translate my es6 code to es5

gulp.task('build_all_debug', ['config', 'compile'], function() {
    var stream = gulp.src(['public/js/config.js', 'public/js/*.js', 'public/compiled/*.js'])
        .pipe(babel({
            presets: ['es2015']
        }))
        .pipe(concat('app.js'))
        .pipe(gulp.dest('public/dist'));
    return stream;
});

While it mostly works fine, it doesn't actually translate Map and Set. My result js code still includes them, and when I run unit test with karma/mocha/phantomJs, I got the following error:

PhantomJS 2.1.1 (Mac OS X 0.0.0) notes.controller "before each" hook: workFn for "loads notes from the service" FAILED
    Can't find variable: Map
    activate@public/dist/app.js:2402:39

Is there any way to force babel to translate Map and Set to object and array in es5?

like image 927
swang Avatar asked Nov 02 '16 19:11

swang


People also ask

Does Babel Transpile to ES5?

Babel is a transpiler because it translates JavaScript ES6 to JavaScript ES5. In contrast, a compiler translates source code from a higher level language to a lower level. An example of compilation would be C++ to machine code or Java to JVM bytecode.

Should I compile to ES5?

For best performance, you should serve ES6 code to browsers that support it, and only serve ES5 code to browsers that don't support ES6. If you need to statically host your code and serve a single version to all browsers, compile to ES5.


2 Answers

You have to include babel-polyfill in your code.

You have to install it with npm:

npm install babel-polyfill

and then, if you're using ES6 modules:

import 'babel-polyfill';

or:

require('babel-polyfill');

If you want to run your code in browser, you can load it from cdnjs:

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.16.0/polyfill.min.js"></script>
like image 82
Michał Perłakowski Avatar answered Oct 20 '22 07:10

Michał Perłakowski


Babel can't "translate" Map and Set, because they aren't language features (although they are described in the ES spec). They're classes that exist in the global scope.

You should use a polyfill that defines the ES6 collections, so you can keep using them in browsers that don't provide support. I'm not sure what library Babel uses, but es6-shim should cover all the major parts.

You won't need to change your code any to use the polyfill, it just defines Map (and friends) for normal use later.

like image 34
ssube Avatar answered Oct 20 '22 06:10

ssube