为什么需要引入 polyfill?

在 esbuild 官方文档中对 target 参数有这么一段描述:

This sets the target environment for the generated JavaScript and/or CSS code. It tells esbuild to transform JavaScript syntax that is too new for these environments into older JavaScript syntax that will work in these environments. For example, the ?? operator was introduced in Chrome 80 so esbuild will convert it into an equivalent (but more verbose) conditional expression when targeting Chrome 79 or earlier.

Note that this is only concerned with syntax features, not APIs. It does not automatically add polyfills for new APIs that are not used by these environments. You will have to explicitly import polyfills for the APIs you need (e.g. by importing core-js). Automatic polyfill injection is outside of esbuild’s scope.

翻译: 这是为生成的JavaScript和/或CSS代码设置目标环境。它告诉esbuild将那些对这些环境来说太新的JavaScript语法转换为在这些环境中可以使用的旧JavaScript语法。例如,?操作符是在Chrome 80中引入的,所以esbuild在针对Chrome 79或更早的环境时,会将其转换为一个等价的(但更冗长)条件表达式。

请注意,这只涉及到语法特性,而不是API。它不会自动为这些环境不使用的新API添加polyfills。你必须明确地为你需要的API导入polyfills(例如,通过导入core-js)。自动注入polyfill是在esbuild的范围之外。

Polyfill.io

综合来看,Polyfill.io 的方案是最精妙的,这个方案有两个特点:

  1. 只引入当前浏览器所需要的 polyfill。
  2. 只需要增加一个 script,对代码侵入性很小。

勾选所有的 es 标准,得到一个 script,把它放在 Html 文件中。

  1. <script src="https://polyfill.io/v3/polyfill.js?features=es2015%2Ces2016%2Ces2017%2Ces2018%2Ces2019%2Ces2020%2Ces2021%2Ces2022"></script>

参考资料