简体   繁体   English

Babel es2015预设不会将Map和Set转换为es5

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

I'm using gulp-babel to translate my es6 code to es5 我正在使用gulp-babel将我的es6代码翻译成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. 虽然它大部分工作正常,但它实际上并没有翻译Map和Set。 My result js code still includes them, and when I run unit test with karma/mocha/phantomJs, I got the following error: 我的结果js代码仍然包含它们,当我用karma / mocha / phantomJs运行单元测试时,我得到以下错误:

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将Map和Set转换为es5中的对象和数组?

You have to include babel-polyfill in your code. 您必须在代码中包含babel-polyfill

You have to install it with npm: 你必须用npm安装它:

npm install babel-polyfill

and then, if you're using ES6 modules: 然后,如果您使用的是ES6模块:

import 'babel-polyfill';

or: 要么:

require('babel-polyfill');

If you want to run your code in browser, you can load it from cdnjs: 如果要在浏览器中运行代码,可以从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). Babel无法“翻译” MapSet ,因为它们不是语言功能(虽然它们在ES规范中有描述)。 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. 您应该使用定义ES6集合的polyfill,以便您可以在不提供支持的浏览器中继续使用它们。 I'm not sure what library Babel uses, but es6-shim should cover all the major parts. 我不确定Babel使用的库是什么,但是es6-shim应该涵盖所有主要部分。

You won't need to change your code any to use the polyfill, it just defines Map (and friends) for normal use later. 您不需要更改任何代码以使用polyfill,它只是定义Map (和朋友)以供日后使用。

Babel does not transpile Map and Set to ES5. Babel不会将MapSet为ES5。

Instead, use their polyfill : 相反,使用他们的polyfill

In order to support Maps, Sets, WeakMaps, and WeakSets in all environments you must include the Babel polyfill. 要在所有环境中支持Maps,Sets,WeakMaps和WeakSets,您必须包含Babel polyfill。

Source 资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM