Vite2兼容低版本chrome(如搜狗80),通过polyfills处理部分需求高版本的语法

23 篇文章 0 订阅
17 篇文章 0 订阅

初步处理

  • 引入处理兼容问题的插件
npm install @vitejs/plugin-legacy -D
  • 配置vite.config.js
  • targets:默认是package.json中的browserslist 建议的值
  • additionalLegacyPolyfills
  • polyfills
  • modernPolyfills:启用此选项将为新式构建生成单独的 polyfills 块,官方不推荐使用,因为其自动检测的特性,配置后,即时浏览器支持,依然会使用nomodule进行加载polyfills的脚本(我这里是replaceAll()配置在polyfills,不生效,估计算前沿功能了,所以要么改写法,要么就得配在这里)
import legacy from '@vitejs/plugin-legacy'
plugins: [
			vue(),
			vueSetupExtend(),
			AutoImport({
				imports: ['vue', 'vue-router', 'vuex'],
			}),
			legacy({
			// 尝试兼容低版本浏览器(不包括ie11)
				targets: ['chrome 80'],
				additionalLegacyPolyfills: ['regenerator-runtime/runtime'] //配置了对ie11也没用
			})
		]

配置后,会根据浏览器的支持动态加载不同的脚本,<script nomodule>在不支持本机 ESM 的浏览器中有条件地加载 polyfills 和旧版捆绑包。
在这里插入图片描述

问题定位(语法问题)

vite打包后还是es6语法,有些语法要求版本比较高,需要通过polyfillspolyfills是通过在低版本浏览器中模拟等效的代码,来实现高版本语法的行为)进行处理

  • replaceAll ()支持的至少chrome85

TypeError: wye(...).replaceAll is not a function
在这里插入图片描述

兼容语法

  • polyfill无法直接使用,需要在plugin-legacy中使用,
legacy({
				targets: ['chrome 80', 'ie >= 11'],
				additionalLegacyPolyfills: ['regenerator-runtime/runtime'], // regenerator-runtime/runtime   @dian/polyfill
				renderLegacyChunks: true,
				polyfills: [
					'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.string.replace-all'
				]
			})
  • modernPolyfills(成功处理)
legacy({
				targets: ['chrome 80', 'ie >= 11'],
				additionalLegacyPolyfills: ['regenerator-runtime/runtime'], // regenerator-runtime/runtime   @dian/polyfill
				renderLegacyChunks: true,
				polyfills: [
					'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'
				],
				modernPolyfills: ['es.string.replace-all']
			})

modernPolyfillspolyfills的差异还不太清楚,慢慢再完善。。。

  • 主流的 polyfills 库为 core-js
    在这里插入图片描述
  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值