defu
Deeply merge objects with defaults — a tiny utility for layered configuration that handles nested objects correctly.
defu
General JSDeeply merge objects with defaults — a tiny utility for layered configuration that handles nested objects correctly.
Fit
Bundle (gzip)
569 B
1.1 kB raw
Install size includes transitive dependencies. Bundle size is gzipped browser payload.
Freshness
The Problem
Object.assign and spread syntax only shallow-merge objects — nested objects are overwritten entirely, not merged. Deeply merging a user config with defaults requires recursion that most teams reinvent repeatedly.
What It Does
defu(userConfig, defaults) recursively merges defaults into the user object, but only fills in keys that are undefined or missing. Arrays can be merged or concatenated. The defuFn variant applies function defaults for computed values. Common in configuration management and library defaults.
Installation
npm install defuUsage Example
import { defu } from 'defu';
const userConfig = {
server: { port: 8080 },
logging: { level: 'debug' },
};
const defaults = {
server: { port: 3000, host: 'localhost', https: false },
logging: { level: 'info', format: 'json' },
cache: { ttl: 300 },
};
const config = defu(userConfig, defaults);
// {
// server: { port: 8080, host: 'localhost', https: false }, // user port wins
// logging: { level: 'debug', format: 'json' }, // user level wins
// cache: { ttl: 300 }, // default added
// }Related packages
Unified TypeScript SDK for building AI-powered apps — switch between 20+ LLM providers without rewriting code.
animejsGeneral JSLightweight JavaScript animation library with a tiny footprint and a powerful, expressive API.
AOSGeneral JSAn easy-to-use library that makes elements fade, slide, or zoom into view as the user scrolls down your page.
archiverGeneral JSStreaming interface for generating ZIP and TAR archives in Node.js — create compressed archives programmatically from files, directories, and buffers.
@formkit/auto-animateGeneral JS> Add smooth transitions to any element with a single line — zero-config animations for adds, removes, and moves.