【umi】polyfill 修补补丁与 babel-loader 转换语法

252 阅读1分钟

github.com/umijs/umi/d…

在umi社区看的一个问题, 就是为啥编译后的产物之后还是有.athasOwnProperty语法,而?.??已经被转换了, 似乎我陷入一个误区,把语法和api弄到一起

umi: 4.0.89,内置的 core-js是3.28.0版本的 最高支持到es2023,现在已经到3.34.0 ,可以支持es2024

image.png

image.png

后面经过大佬点拨,终于明白。 实际上,polyfill就是一个补丁,polyfill就是在原型链造一个方法,所以在构建产物中出现.at的api是正常的, 而?.??需要通过babel-loader去转换

举例,.at语法在polyfill中, 通原型链来实现

function at(n) {
  // ToInteger() abstract op
  n = Math.trunc(n) || 0;
  // Allow negative indexing from the end
  if (n < 0) n += this.length;
  // OOB access is guaranteed to return undefined
  if (n < 0 || n >= this.length) return undefined;
  // Otherwise, this is just normal property access
  return this[n];
}

const TypedArray = Reflect.getPrototypeOf(Int8Array);

for (const C of [Array, String, TypedArray]) {
  Object.defineProperty(C.prototype, 'at', {
    value: a1,
    writable: true,
    enumerable: false,
    configurable: true,
  });
}

而对于语法类?.则是通过babel来转换 假设你已经安装了babel-loader @babel/core @babel/preset-env

module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            cacheDirectory: true,
            presets: [
              [
                '@babel/preset-env',
                {
                  targets: {
                    browsers: ['last 2 versions', 'ie >= 11'],
                  },
                  useBuiltIns: 'usage',
                  corejs: 3,
                },
              ],
            ],
          },
        },
      },
    ],
  },
  // ...
};

所以总结下来, 一个是语法,一个是补丁, 补丁是利用原型链挂载的,所以在产物中有at api 是正常的,即使到了低版本的浏览器也不会报错,因为当使用at的时候,用的是原型链上面的