Files
workspace/code/docusaurus/docs/coding/vue/低版本浏览器适配.md
T
2026-03-18 17:14:34 +08:00

2.7 KiB
Raw Blame History

环境:

  • 浏览器:Chrome56
  • Vue:^3.5.15
  • Vite:6.3.5

解决方案:

@vitejs/plugin-legacy ,该包是Vite提供的一个插件,为打包后的文件提供传统浏览器兼容性支持。官网:https://github.com/vitejs/vite/tree/main/packages/plugin-legacy

terser,主要用于压缩代码,还有代码混淆、源码映射等功能。

pnpm i @vitejs/plugin-legacy terser -D

安装上述依赖后,在 vite.config.ts/js 中添加以下内容:

import legacy from '@vitejs/plugin-legacy'
// 在插件处添加一下功能
plugins: [
  legacy({
    // 目标浏览器环境,'defaults' 是浏览器列表默认设置,支持 Chrome 56 及以上
    targets: ['defaults', 'Chrome >= 56'],

    // 额外引入的兼容性 polyfill,这里加入了对 generator 函数的支持
    additionalLegacyPolyfills: ['regenerator-runtime/runtime'],

    // 是否生成兼容旧浏览器的代码块(chunk)
    renderLegacyChunks: true,

    // 需要引入的具体 polyfill 列表,确保目标环境缺失的 API 得到支持
    polyfills: [
      'es.symbol',                         // Symbol 支持
      'es.array.filter',                   // Array.prototype.filter 支持
      'es.promise',                       // Promise 支持
      'es.promise.finally',                // Promise.prototype.finally 支持
      'es.object.assign',                  // Object.assign 支持
      'es.map',                           // Map 支持
      'es.set',                           // Set 支持
      'es.array.for-each',                 // Array.prototype.forEach 支持
      'es.object.define-properties',      // Object.defineProperties 支持
      'es.object.define-property',        // Object.defineProperty 支持
      'es.object.get-own-property-descriptor',      // Object.getOwnPropertyDescriptor 支持
      'es.object.get-own-property-descriptors',     // Object.getOwnPropertyDescriptors 支持
      'es.object.keys',                   // Object.keys 支持
      'es.object.to-string',              // Object.prototype.toString 支持
      'web.dom-collections.for-each',     // DOM 集合的 forEach 支持
      'esnext.global-this',               // 全局变量 globalThis 支持
      'esnext.string.match-all',           // String.prototype.matchAll 支持
      'es.array.iterator',                // 数组迭代器支持
      'es.string.includes',               // String.prototype.includes 支持
      'es.string.starts-with',            // String.prototype.startsWith 支持
      'es.object.values',                 // Object.values 支持
    ],
  }),
]

targets 可以参考:Browserslist官网 查询

注意该方案只在打包后生效。