CSS @font-face src Property Parser

2.1.0 · active · verified Tue Apr 21

css-font-face-src is a focused JavaScript and TypeScript library designed to parse and serialize the `src` property value of CSS `@font-face` rules. It transforms complex CSS `src` strings into an array of structured objects, distinguishing between local font references and remote URLs (with optional format and `tech()` fragments), and can convert these objects back into a valid CSS string. The current stable version is 2.1.0. The package has a moderate release cadence, with significant updates in major versions like v2.0.0 introducing TypeScript support and minor versions adding support for newer CSS specifications (e.g., CSS Fonts Module Level 4 `tech()` fragment in v2.1.0). Its primary differentiator is its dedicated, precise parsing capability for this specific CSS property, providing a reliable programmatic interface for manipulating font declarations.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates parsing a CSS `src` string, inspecting the resulting object structure, modifying it, and then serializing it back into a CSS string, showcasing both `parse` and `serialize` functions along with TypeScript type usage.

import { parse, serialize, FontFaceSrcItem } from 'css-font-face-src';

const cssSrcString = 'local("The Font"), url("font.otf") format("opentype"), url("font.woff"), local("Another Font"), url("font.svg") tech("svg")';

// Parse the CSS src string into a structured array of objects
const parsedItems = parse(cssSrcString);

console.log('Parsed items:');
console.log(JSON.stringify(parsedItems, null, 2));

// Modify the parsed items (e.g., add a new font source)
const modifiedItems: FontFaceSrcItem[] = [
  ...parsedItems,
  { url: 'https://example.com/new-font.ttf', format: 'truetype' }
];

// Serialize the (potentially modified) object array back to a CSS string
const serializedString = serialize(modifiedItems);

console.log('\nModified and serialized string:');
console.log(serializedString);

/* Expected Output:
Parsed items:
[
  {
    "local": "The Font"
  },
  {
    "url": "font.otf",
    "format": "opentype"
  },
  {
    "url": "font.woff"
  },
  {
    "local": "Another Font"
  },
  {
    "url": "font.svg",
    "tech": "svg"
  }
]

Modified and serialized string:
local("The Font"), url("font.otf") format("opentype"), url("font.woff"), local("Another Font"), url("font.svg") tech("svg"), url("https://example.com/new-font.ttf") format("truetype")
*/

view raw JSON →