Sugar.js Utility Library
Sugar.js is a comprehensive JavaScript utility library that extends native object prototypes (e.g., String, Number, Array, Date) with additional methods for common operations. It provides functional programming utilities, robust date/time manipulation, and various helper functions. The current stable version is 2.0.6. While it offers polyfills, its primary design philosophy is to augment existing prototypes rather than providing standalone utility functions, which differentiates it from libraries like Lodash or Ramda. Releases appear to be driven by feature enhancements and bug fixes, with a major version bump from v1 to v2 bringing significant changes and requiring a dedicated upgrade path. It supports both browser and Node.js environments and ships with TypeScript type definitions.
Common errors
-
TypeError: 'someMethod' is not a function
cause Attempting to use a Sugar.js method on a native object when Sugar.js (or the relevant module/method) has not been loaded or correctly imported.fixEnsure `require('sugar')` or the specific module/method (`require('sugar/number')` or `require('sugar/number/round')`) is called before using the method. -
ReferenceError: Sugar is not defined
cause Trying to access the global `Sugar` object in a Node.js (CommonJS) or ESM environment without explicitly importing it first.fixIn Node.js CommonJS, use `const Sugar = require('sugar');`. For TypeScript, `import Sugar = require('sugar');`. The `Sugar` object is not globally available by default in these module systems. -
TypeError: Cannot read properties of undefined (reading 'round') (or similar for other modules)
cause This typically occurs if you try to access a module's methods (e.g., `Sugar.Number.round`) after only importing an individual method or a non-module-specific entry point, or if trying to destructure incorrectly.fixIf you intend to use a module's full API, ensure you `require('sugar/module_name')`, which will populate the `Sugar` object with that module's methods. For example, `const Sugar = require('sugar/number'); Sugar.Number.round(...)`. -
Date formatting not showing expected language/locale
cause The required date locale file (`sugar/locales/xx`) has not been loaded, so Sugar defaults to English or a generic format.fixAdd `require('sugar/locales/your_locale_code')` to your application to load the desired locale as a side effect. For example, `require('sugar/locales/es')` for Spanish.
Warnings
- breaking Upgrading from Sugar.js v1 to v2 introduces significant breaking changes. Refer to the official 'CAUTIONLOG' and use the upgrade helper script for assistance.
- gotcha Sugar.js extensively modifies native object prototypes (e.g., `String.prototype`, `Array.prototype`, `Date.prototype`). This can lead to conflicts with other libraries that also modify native prototypes, or unexpected behavior in environments expecting unadulterated natives.
- breaking The `String#namespace` method was removed in v1.3.9 due to conflicts with jQuery and its limited utility. Code relying on this method will break.
- gotcha When using Sugar.js from npm in Node.js, polyfills (e.g., for ES6 features) are not automatically included with the main `require('sugar')` entry point. They must be explicitly required.
- gotcha Date locales are not loaded by default and must be explicitly required as a side effect. Failing to do so will result in default English formatting even if Sugar's date methods are used.
Install
-
npm install sugar -
yarn add sugar -
pnpm add sugar
Imports
- Sugar
import Sugar from 'sugar'; import { Sugar } from 'sugar';import Sugar = require('sugar'); - Sugar.Number (module)
import { Number } from 'sugar';import Sugar = require('sugar/number'); - round (individual method)
import { round } from 'sugar/number';import round = require('sugar/number/round'); - Date Locales
import { ja } from 'sugar/locales';require('sugar/locales/ja'); - SugarStatic (type)
import type { SugarStatic } from 'sugar';
Quickstart
import Sugar = require('sugar');
import round = require('sugar/number/round');
// Demonstrate Number module extension
const num = 3.14159;
console.log(`Original number: ${num}`);
console.log(`Rounded to 2 decimal places: ${Sugar.Number.round(num, 2)}`);
console.log(`Ceiling: ${Sugar.Number.ceil(num)}`);
// Demonstrate individual method import
const valueToRound = 4.567;
console.log(`Value for direct round import: ${valueToRound}`);
console.log(`Rounded using direct import: ${round(valueToRound)}`);
// Demonstrate Array module extension
const arr = [1, 2, 3, 4, 5];
console.log(`Original array: ${arr}`);
console.log(`Array first element: ${Sugar.Array.first(arr)}`);
console.log(`Array last element: ${Sugar.Array.last(arr)}`);
console.log(`Array shuffled: ${Sugar.Array.shuffle(arr)}`);
// Demonstrate Date module and locale
require('sugar/locales/fr'); // Load French locale as a side effect
const today = new Date(); // Native Date object
console.log(`Today's date (default format): ${today.format()}`); // Sugar extends Date.prototype
console.log(`Today's date (French format): ${today.format('{Weekday}, {Month} {day}, {year}', 'fr')}`);
// Demonstrate chaining with prototype extensions
const originalString = ' hello world ';
console.log(`Original string: "${originalString}"`);
const chainedResult = originalString.trim().capitalize();
console.log(`Chained string operation: "${chainedResult}"`);