vite+vue3+ts项目兼容低版本浏览器@vitejs/plugin-legacy

3,623 阅读2分钟

项目环境:

    "vite": "^4.3.9",
    "typescript": "^5.0.2",
    "vue": "^3.2.47",node版本: v14.16.0

查了资料,安装:

npm install --save-dev @vitejs/plugin-legacy@1.7.1

遇到问题:

failed to load config from vite.config.ts error during build: Error: Cannot find module 'node:path'

查了资料,得知是node版本问题不支持‘node:’语法,并且是只有node 16.0.0+ 还有v14.18.0+, node 15不支持

于是将版本升级v16.18.0

再build,还是报错,重新安装

npm install --save @vitejs/plugin-legacy

查文档,还得安装terser

npm add -D terser

结果第一次build成功了,vitejs/plugin-legacy安装成了1.8.2版本

结果第二次build就失败了,继续找原因

err ERESOLVE
plugin-legacy@1.8.2 ERESOLVE could not resolve

重新安装vitejs/plugin-legacy

npm install --save-dev @vitejs/plugin-legacy

发现版本变成"^4.1.1",配置

vite.config.ts

import legacy from '@vitejs/plugin-legacy'


..
plugins: [
 legacy({        
  // 设置目标浏览器,browserslist 配置语法        
  targets: ['Android >= 7', 'chrome < 60', 'edge < 15'],             
})]

即配置支持安卓版本大于等于7,chrome < 60, edge < 15 是配置该插件传统浏览器的兼容

到此,使用低版本安卓可以打开页面了;

下面是几个配置项:

renderLegacyChunks:

Default: true

Set to false to disable legacy chunks. This is only useful if you are using modernPolyfills, which essentially allows you to use this plugin for injecting polyfills to the modern build only

意思是默认开启,设置成false去关闭传统包,并且只有使用了modernPolyfills才是有效的,可以允许你使用插件只在现代模式构建的时候去插入补丁

modern:

  • Default: false

    Defaults to false. Enabling this option will generate a separate polyfills chunk for the modern build (targeting browsers with native ESM support).

    Set to a list of strings to explicitly control which polyfills to include. See Polyfill Specifiers for details.

    Note it is not recommended to use the true value (which uses auto-detection) because core-js@3 is very aggressive in polyfill inclusions due to all the bleeding edge features it supports. Even when targeting native ESM support, it injects 15kb of polyfills!

    If you don't have hard reliance on bleeding edge runtime features, it is not that hard to avoid having to use polyfills in the modern build altogether. Alternatively, consider using an on-demand service like Polyfill.io to only inject necessary polyfills based on actual browser user-agents (most modern browsers will need nothing!).

请注意,不建议使用 true 值(使用自动检测),因为 core-js@3 支持的所有功能都非常先进,因此在多填充中非常激进。即使是针对原生 ESM 支持,它也会注入 15kb 的 polyfills!如果您不太依赖于边缘运行时功能,那么在现代构建中完全避免使用 polyfills 并不难。或者,也可以考虑使用 Polyfill.io 这样的按需服务,只根据实际的浏览器用户代理注入必要的 polyfills(大多数现代浏览器都不需要