Vite低版本浏览器兼容 钉钉

1,169 阅读1分钟

vite plugin-legacy详解

vite 的runtime是基于 native ESM 的,所以如果开发者需要打包代码在 传统浏览器 or 兼容性差的浏览器版本, 就需要用到此插件,话不多说直接上代码

pnpm i @vitejs/plugin-legacy -D

安装完成之后可以在vite.config.js添加配置项。

import legacyPlugin from '@vite/plugin-legacy'

export default defaultConfig({
   plugins: [
     // 浏览器兼容问题配置
      legacyPlugin({
        targets: ['chrome 69'], // 需要兼容的目标列表,可以设置多个
        additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
        // 针对现代浏览器的polyfill
        modernPolyfills: [
          'es.symbol',
          'es.array.filter',
          'es.promise',
          'es.promise.finally',
          'es/map',
          'es/set',
          'es.array.for-each',
          'es.object.define-properties',
          'es.object.define-property',
          'es.object.get-own-property-descriptor',
          'es.object.get-own-property-descriptors',
          'es.object.keys',
          'es.object.to-string',
          'web.dom-collections.for-each',
          'esnext.global-this',
          'esnext.string.match-all',
          'es.object.entries',
          'es.object.from-entries',
          'esnext.object.iterate-entries',
        ],
      }),
   ]
})

targets

兼容浏览器配置:browsersl

> 1%
last 2 versions
ios >= 12

在targets这样写

 targets: ['> 1%', 'last 2 versions', 'ios >= 12'],
 

## additionalLegacyPolyfills

针对传统浏览器的额外polyfills,之所有有这个字段,是因为 plugin-legacy内部只包含了core-js相关的polyfills,如果开发者希望添加非corejs的polyfill,就加在这个字段里面

modernPolyfills

modernPolyfills是针对现代浏览器的polyfill,这样就只会打包出针对现代浏览器的polyfill,而不会生成传统的polyfill

polyfills

polyfills是针对传统浏览器的polyfill, Polyfills跟modernPolyfill的功能是一样的,他们的区别仅仅在于语法,就如上文所讲到的代码编译

开启了 renderLegacyChunks才会代码编译生成 legacy chunk


legacyPlugin({
  renderLegacyChunks: true,
  polyfills: ['es.global-this'],
})