Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

babel-polyfill #188

Open
TieMuZhen opened this issue Apr 29, 2022 · 0 comments
Open

babel-polyfill #188

TieMuZhen opened this issue Apr 29, 2022 · 0 comments
Labels

Comments

@TieMuZhen
Copy link
Owner

TieMuZhen commented Apr 29, 2022

刚接触 babel 的同学一开始可能都认为在使用了 babel 后就可以无痛的使用 es2015 了,之后被各种 undefined 的报错无情打脸。一句话概括, babel 的编译不会做 polyfill。那么 polyfill 是指什么呢?

const foo = (a, b) => {
    return Object.assign(a, b);
};

当我们写出上面这样的代码,交给 babel 编译时,我们得到了:

"use strict";

var foo = function foo(a, b) {
    return Object.assign(a, b);
};

箭头函数被编译成了普通的函数,但仔细一看Object.assign还没有被编译,而它作为es5的新方法,并不能运行在相当多的浏览器上。为什么不把Object.assign编译成(Object.assign||function() { /*...*/})这样的替代方法呢?
好问题!编译为了保证正确的语义,只能转换语法而不是去增加或修改原有的属性和方法。所以babel不处理Object.assign反倒是最正确的做法。而处理这些方法的方案则被称为polyfill

babel-polyfill

babel 直接提供了通过改变全局来兼容es5所有方法的babel-polyfill,安装babel-polyfill后你只需要在所有代码的最前面加一句 import 'babel-polyfill'便可引入它,如果使用了 webpack 也可以直接在entry中添加babel-polyfill的入口。

import 'babel-polyfill';
export const foo = (a, b) => Object.assign(a, b);

所以在实际开发中遇到一些ES5语法并不支持高级的特性时,我们引入对应特性的polyfill即可

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant