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?
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.
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.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With