defu

repository·main·Indexed 23 days ago

https://github.com/unjs/defu

A lightweight utility for recursively assigning default properties to objects. It supports deep merging, array concatenation, and prototype pollution prevention. Key features include createDefu for custom merging strategies, defuFn for function-based value manipulation, and defuArrayFn for array-specific function merging. It provides a Defu type utility for TypeScript and supports both ESM and CommonJS environments.

Tokens
2.2K
Snippets
9
Records
17
Agent score
79%

What's inside defu

  1. Install defu

    main

    You can install defu using any of the following package managers:

    # yarn
    yarn add defu
    
    # npm
    npm install defu
    
    # pnpm
    pnpm install defu
    ```bash
    # yarn
    yarn add defu
    # npm
    npm install defu
    # pnpm
    pnpm install defu
    ```埋
  2. Apply functions only to array defaults with defuArrayFn

    main

    defuArrayFn is similar to defuFn, but the functions provided are only applied to array values defined in the defaults.

    Note: The function is called only if the value defined in the defaults is an array.

    import { defuArrayFn } from "defu";
    
    defuArrayFn(
      {
        ignore: (val) => val.filter((i) => i !== "dist"),
        count: () => 20,
      },
      {
        ignore: ["node_modules", "dist"],
        count: 10,
      },
    );
    /*
      {
        ignore: ['node_modules'],
        count: () => 20
      }
    */
  3. Use defu to assign default properties recursively

    main

    The defu function assigns default properties to a destination object recursively. The leftmost arguments have the highest priority.

    Note:

    • object and defaults are not modified.
    • Nullish values (null and undefined) are skipped.
    • __proto__ and constructor keys are skipped to prevent object pollution.
    • Array values are concatenated if the property is defined in the defaults.
    import { defu } from "defu";
    
    const options = defu(object, ...defaults);
    import { defu } from "defu";
    
    console.log(defu({ a: { b: 2 } }, { a: { b: 1, c: 3 } }));
    // => { a: { b: 2, c: 3 } }
  4. Manipulate default values with defuFn

    main

    defuFn allows you to provide a function for specific keys. If a function is provided in the first argument, it will be called with the default value instead of performing a standard merge. This is useful for manipulating default values (e.g., filtering arrays or transforming numbers).

    Note: If the default value is not defined, the function will not be called and the value will be kept as is.

    import { defuFn } from "defu";
    
    defuFn(
      {
        ignore: (val) => val.filter((item) => item !== "dist"),
        count: (count) => count + 20,
      },
      {
        ignore: ["node_modules", "dist"],
        count: 10,
      },
    );
    /*
     {
        ignore: ['node_modules'],
        count: 30
      }
     */
  5. Create a custom merger with createDefu

    main

    If the default merging strategy is not suitable, use createDefu to create a custom instance. The custom merger function accepts obj (the source object), key, and value (the current value). It should return true if the custom merging was applied.

    import { createDefu } from "defu";
    
    const ext = createDefu((obj, key, value) => {
      if (typeof obj[key] === "number" && typeof value === "number") {
        obj[key] += value;
        return true;
      }
    });
    
    ext({ cost: 15 }, { cost: 10 }); // { cost: 25 }
  6. Use defuProxy for object merging

    main
    The defuProxy function is the primary entrypoint for merging objects. It takes a source object and one or more defaults objects. It returns a Defu instance that represents the merged result. The function is designed to handle cases where the source might be undefined, null, or other ignored inputs by falling back to the provided defaults.
  7. Merge objects with defu()

    main

    The defu function is the standard utility for merging objects with defaults. It performs a deep merge where properties from the first argument (baseObject) overwrite properties in the second argument (defaults).

    Key behaviors:

    • Deep Merging: Nested plain objects are merged recursively.
    • Array Concatenation: If both the base value and the default value are arrays, they are concatenated ([...base, ...defaults]).
    • Safety: It ignores __proto__ and constructor keys to prevent prototype pollution.
    • Multi-argument support: You can pass multiple objects to be merged sequentially.
  8. Access defuProxy utilities and extensions

    main

    The defuProxy function acts as a namespace providing several utilities for advanced merging scenarios:

    • defuProxy.fn: A DefuFn utility.
    • defuProxy.arrayFn: An arrayFn utility for array-specific merging.
    • defuProxy.defuFn: A DefuFn utility.
    • defuProxy.defuArrayFn: A defuArrayFn utility.
    • defuProxy.createDefu: A function to create new defu instances.
    • defuProxy.extend(merger): Returns a DefuFn configured with a custom merger function.
    • defuProxy.defu: The default instance.
    • defuProxy.default: An alias for the default instance.
  9. Create a custom defu instance with createDefu()

    main
    Use createDefu to generate a new merging function with a custom Merger logic. A Merger is a function that receives (object, key, currentValue, namespace) and returns a boolean. If the merger returns true, the default merging logic for that specific key is skipped, allowing you to implement custom resolution rules.
  10. Import defu in CommonJS

    main
    To use defu in a CommonJS environment, you can require the package. The main export is the defu function itself, but the package also exports named properties for its utility functions.
  11. Use the exported defu utilities in CommonJS

    main

    The CommonJS entrypoint provides access to the following functions via named exports:

    • defu: The core merging function.
    • createDefu: A utility to create a custom defu instance.
    • defuFn: A utility for merging functions.
    • defuArrayFn: A utility for merging arrays of functions.