Appearance
vite项目兼容旧版本浏览器
vite项目兼容旧版本浏览器,需要用到@vitejs/plugin-legacy
这个插件
TIP
构建阶段: Vite 会生成两套代码
- 现代代码:保留原生 ESM 和现代语法,通过
<script type="module">
加载。 - 旧版代码:降级后的代码,通过
<script nomodule>
加载。
运行阶段:
- 现代浏览器会加载
<script type="module">
,忽略 nomodule。 - 旧版浏览器会加载 nomodule 的降级代码。
安装命令
bash
pnpm add @vitejs/plugin-legacy -D
pnpm add @vitejs/plugin-legacy -D
配置使用
在vite.config.js
中引入并配置插件
js
import legacy from '@vitejs/plugin-legacy'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [
legacy({
targets: ['defaults', 'not IE 11'], // 指定兼容目标
polyfills: ['es.promise', 'es.array.iterator'], // 手动指定需要的 Polyfill
modernPolyfills: ['es.promise.finally'], // 为现代浏览器也需要的 Polyfill
}),
],
})
import legacy from '@vitejs/plugin-legacy'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [
legacy({
targets: ['defaults', 'not IE 11'], // 指定兼容目标
polyfills: ['es.promise', 'es.array.iterator'], // 手动指定需要的 Polyfill
modernPolyfills: ['es.promise.finally'], // 为现代浏览器也需要的 Polyfill
}),
],
})
注意
- Polyfill 体积:自动注入的 Polyfill 可能增加包体积,建议通过 targets 精确控制兼容范围。
- 动态导入:旧版模式下的动态导入(import())可能需要额外 Polyfill(如 systemjs)。
- 与其它插件顺序:确保 legacy() 插件在其他转换插件(如 @vitejs/plugin-vue)之后。