What is @ungap/structured-clone?
The @ungap/structured-clone package provides a polyfill for the structuredClone function, which allows for deep cloning of objects, including complex types that are not handled by JSON serialization, such as Dates, Maps, Sets, etc. This functionality is particularly useful for copying values where a simple reference copy is not sufficient or desired.
What are @ungap/structured-clone's main functionalities?
Cloning complex objects
This feature allows for the deep cloning of complex objects, including those containing types that cannot be cloned using JSON methods. It's useful for duplicating objects that include nested structures, Dates, Maps, Sets, etc., without the original object being affected by changes to the clone.
const clonedObject = structuredClone(originalObject);
Other packages similar to @ungap/structured-clone
clone
The 'clone' package offers deep cloning of objects and supports circular references. Unlike @ungap/structured-clone, it does not rely on the structuredClone API and provides more customization options for cloning behaviors but might not handle all modern JavaScript types as seamlessly.
lodash.clonedeep
Provided by the Lodash library, lodash.clonedeep performs a deep clone of an object. While it is very effective for a wide range of JavaScript objects, it may not support cloning of newer types such as Blobs or FileLists as directly as @ungap/structured-clone does, focusing instead on compatibility with a wide range of JavaScript environments.
structuredClone polyfill
An env agnostic serializer and deserializer with recursion ability and types beyond JSON from the HTML standard itself.
- Supported Types
- not supported yet: Blob, File, FileList, ImageBitmap, ImageData, and ArrayBuffer, but typed arrays are supported without major issues, but u/int8, u/int16, and u/int32 are the only safely suppored (right now).
- not possible to implement: the
{transfer: []}
option can be passed but it's completely ignored.
- MDN Documentation
- Serializer
- Deserializer
Serialized values can be safely stringified as JSON too, and deserialization resurrect all values, even recursive, or more complex than what JSON allows.
Examples
Check the 100% test coverage to know even more.
import structuredClone from '@ungap/structured-clone';
const cloned = structuredClone({any: 'serializable'});
import {serialize, deserialize} from '@ungap/structured-clone';
const serialized = serialize({any: 'serializable'});
const deserialized = deserialize(serialized);
Global Polyfill
Note: Only monkey patch the global if needed. This polyfill works just fine as an explicit import: import structuredClone from "@ungap/structured-clone"
import structuredClone from "@ungap/structured-clone";
if (!("structuredClone" in globalThis)) {
globalThis.structuredClone = structuredClone;
}
import structuredClone from "@ungap/structured-clone"
structuredClone()
Note: Do not attach this module's default export directly to the global scope, whithout a conditional guard to detect a native implementation. In environments where there is a native global implementation of structuredClone()
already, assignment to the global object will result in an infinite loop when globalThis.structuredClone()
is called. See the example above for a safe way to provide the polyfill globally in your project.
There is no middle-ground between the structured clone algorithm and JSON:
- JSON is more relaxed about incompatible values: it just ignores these
- Structured clone is inflexible regarding incompatible values, yet it makes specialized instances impossible to reconstruct, plus it doesn't offer any helper, such as
toJSON()
, to make serialization possible, or better, with specific cases
This module specialized serialize
export offers, within the optional extra argument, a lossy property to avoid throwing when incompatible types are found down the road (function, symbol, ...), so that it is possible to send with less worrying about thrown errors.
import structuredClone from '@ungap/structured-clone';
const cloned = structuredClone(
{
method() {
},
special: Symbol('also ignored')
},
{
lossy: true,
json: true
}
);
The behavior is the same found in JSON when it comes to Array, so that unsupported values will result as null
placeholders instead.
toJSON
If lossy
option is not enough, json
will actually enforce lossy
and also check for toJSON
method when objects are parsed.
Alternative, the json
exports combines all features:
import {stringify, parse} from '@ungap/structured-clone/json';
parse(stringify({any: 'serializable'}));