sprintf-kit is a JavaScript library providing a modular `printf` format string parser and basic formatter. It allows developers to create custom `sprintf`-like functions by explicitly configuring specific modifier resolvers (e.g., for `%s`, `%d`). The library's core is its detailed `printf` syntax parser, which breaks down format strings into literals and placeholder metadata. It also offers a format function generator and a parts resolver generator, enabling granular control over how strings are processed and substitutions are applied. Currently at version 2.0.2, the package has seen infrequent but recent maintenance, with the last major update (v2.0.0) occurring in 2018, focusing on internal structure and advanced parsing capabilities. Its modularity and explicit modifier configuration differentiate it from simpler `sprintf` implementations that might bundle all modifiers by default.
npm install sprintf-kitVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to set up a custom `sprintf` formatter using `sprintf-kit`, including defining specific modifiers and optionally styling literal parts of the string with an external library like `cli-color`.
Ensure you are importing the resolver via `require('sprintf-kit/get-resolver')`.Update any code that processes the `flags` property to expect a string instead of an array. For example, `placeholder.flags.includes('0')` should become `placeholder.flags && placeholder.flags.includes('0')`.Always pass an object mapping modifier types (e.g., `s`, `d`) to their respective resolver functions (e.g., `require('sprintf-kit/modifiers/s')`) when creating your format function.For consistent and predictable behavior, either use parameter indexing for all placeholders or for none. Review `isParameterIndexingValid` to ensure your format string logic is as intended.
Ensure all desired modifiers are explicitly passed to the `require('sprintf-kit')` factory function. For example: `require('sprintf-kit')({ s: require('sprintf-kit/modifiers/s') });`This was a bug fixed in v2.0.1. Ensure your `sprintf-kit` version is 2.0.1 or newer. If on an older version, manually replace `%%` with a single `%` in your format string or upgrade the package.
Ensure the argument types match the expected modifier types. For complex objects, consider providing a custom modifier or a `j` (JSON) modifier if available and appropriate, or explicitly stringify the object before passing it.