structuredClone 原生深拷贝来了,chrome >= 98才支持
现为了响应原生特性,使用babel来使用structuredClone
babel.config.js
presets: [
[
'@babel/preset-env',
{
modules: false, // esm 为false,使用esmodule语法
useBuiltIns: 'usage', // 使用的引入,'entry','usage'
/**
* 使用useBuiltIns 需要定义corejs版本,不定义默认为2
* 注意:这里写corejs: 3的话为3.0,所以一定要带小版本号
*/
corejs: '3.21',
targets: {
// esmodules: true,
chrome: 49
// browsers: ['chrome > 49']
},
// shippedProposals: true
}
]
],
注意点是corejs的配置,原来我写的是corejs:3 这个其实并不是corejs最新版,而是corejs:3.0,因此,没有自动生成structedClone的polyfill。需要手动打上最新版本的版本号。
这样在经过babel代码转换后便会自动在入口上引入相应的polyfill了(使用babel-cli测试通过)
若不生效或打包失败,则考虑全局手动引入core-js的polyfill 如下:
import "core-js/modules/es.array.at.js";
import "core-js/modules/web.structured-clone.js";
参考
引用babel官网原话
This option only has an effect when used alongside
useBuiltIns: usage
oruseBuiltIns: entry
, and ensures@babel/preset-env
injects the polyfills supported by yourcore-js
version. It is recommended to specify the minor version otherwise"3"
will be interpreted as"3.0"
which may not include polyfills for the latest features.
@babel/preset-env · Babel 中文网 (babeljs.cn)
存在问题
报错:Failed to execute 'structuredClone' on 'Window': [object Array] could not be cloned.
原因:无法克隆Proxy代理的对象。因此,在vue3里用不了。