cssesc: CSS String and Identifier Escaping
cssesc is a JavaScript utility library designed for safely escaping arbitrary strings and identifiers for use within CSS. It specializes in producing the shortest possible valid ASCII-only escape sequences, making it efficient for various web development scenarios. Currently at stable version 3.0.0, it offers more granular control than the native `CSS.escape()` method or its polyfills. Key differentiators include the ability to specify if the output is intended for a CSS string literal or a CSS identifier, and control over quote preferences for string wrapping. Its release cadence is typically measured, reflecting its nature as a focused utility library with a stable API. It declares compatibility with Node.js versions 4 and higher, making it widely compatible, though modern usage typically occurs on much newer environments.
Common errors
-
TypeError: cssesc is not a function
cause Attempting to call `cssesc` as a named export (`{ cssesc }`) when it's primarily a default export, or trying to call it on a module object when using `import * as cssesc from 'cssesc';` without accessing `.default`.fixFor ESM, use `import cssesc from 'cssesc';`. For CommonJS, use `const cssesc = require('cssesc');`. If using `import * as cssescModule from 'cssesc';`, call it as `cssescModule.default(...)`. -
Error: Module 'cssesc' does not provide an export named 'cssesc'
cause This error occurs in ESM when attempting to destructure `cssesc` as a named export (`import { cssesc } from 'cssesc';`) while the package only provides a default export for its main functionality.fixChange your import statement to `import cssesc from 'cssesc';` to correctly import the default exported function. -
CSS selector for ID or class with special characters doesn't work
cause The input string was escaped using `cssesc()` without the `isIdentifier: true` option, leading to incorrect escaping for CSS identifiers (e.g., `.` or `-` not being escaped when they should be at the start of a sequence).fixWhen escaping values intended for CSS identifiers (like class names, IDs, custom property names), always use `cssesc(value, { isIdentifier: true })`. This ensures characters like initial digits or special symbols are correctly escaped for identifier rules.
Warnings
- gotcha Incorrectly using the output of `cssesc` for a CSS identifier (e.g., class names, IDs) without setting the `isIdentifier: true` option will lead to improperly escaped CSS that breaks selectors or other identifier contexts. The default behavior is for CSS string literals.
- gotcha When migrating to modern JavaScript module systems (ESM), ensure you use the `import cssesc from 'cssesc';` syntax. The package's documentation prominently features `require('cssesc')`, which is for CommonJS environments.
- gotcha The `package.json` specifies `engines.node: >=4`. While technically compatible with very old Node.js versions, running `cssesc` in such environments is discouraged due to potential security vulnerabilities and lack of modern features in the Node.js runtime itself. Always use a currently supported Node.js LTS version.
Install
-
npm install cssesc -
yarn add cssesc -
pnpm add cssesc
Imports
- cssesc
import { cssesc } from 'cssesc';import cssesc from 'cssesc';
- cssesc
const cssesc = require('cssesc'); - Options
type Options = { isIdentifier?: boolean; quotes?: 'single' | 'double'; wrap?: boolean; }; // Manual definitionimport cssesc, { Options } from 'cssesc';
Quickstart
import cssesc from 'cssesc';
console.log('--- Escaping for CSS String Literal ---');
const unsafeString = 'Hello, world! I ♥ JavaScript and "quotes".';
const escapedString = cssesc(unsafeString);
console.log(`Original: "${unsafeString}"\nEscaped: '${escapedString}'`);
// Expected: 'Hello, world! I \2665 JavaScript and \"quotes\".'
console.log('\n--- Escaping for CSS Identifier ---');
const unsafeIdentifier = '1a-b.c d';
const escapedIdentifier = cssesc(unsafeIdentifier, { isIdentifier: true });
console.log(`Original: "${unsafeIdentifier}"\nEscaped: '${escapedIdentifier}'`);
// Expected: '\31 a-b\.c\ d'
console.log('\n--- Escaping with Double Quotes and Wrapping ---');
const anotherUnsafeString = 'My ID is #foo/bar and it has \'single\' quotes.';
const wrappedDoubleQuoteEscaped = cssesc(anotherUnsafeString, {
quotes: 'double',
wrap: true
});
console.log(`Original: "${anotherUnsafeString}"\nEscaped: ${wrappedDoubleQuoteEscaped}`);
// Expected: "My ID is #foo/bar and it has 'single' quotes."
console.log('\n--- Escaping a non-ASCII character (emojis) ---');
const emojiString = 'User😊Name';
const escapedEmoji = cssesc(emojiString, { isIdentifier: true });
console.log(`Original: "${emojiString}"\nEscaped: '${escapedEmoji}'`);
// Expected: 'User\1F60A Name'