juice

repository·master·Indexed 25 days ago

https://github.com/automattic/juice

A library that inlines CSS properties into the style attribute of HTML elements, specifically designed for HTML email development and environments that do not support external stylesheets. It provides a variety of API methods for processing HTML strings, files, and cheerio DOM objects, as well as a CLI and a browser-compatible client.

Tokens
3.4K
Snippets
3
Records
20
Agent score
82%

What's inside juice

  1. Install and use Juice to inline CSS

    master

    Juice takes HTML and inlines its CSS properties directly into the style attribute of the elements. This is primarily used for preparing HTML emails or embedding HTML in 3rd-party websites where external stylesheets might not be supported or loaded.

    import juice from 'juice';
    
    const result = juice("<style>div{color:red;}</style><div/>");
    // result: <div style="color: red;"></div>
  2. Use special HTML markup for Juice control

    master

    Use these attributes in your HTML to override Juice behavior for specific elements:

    • data-embed: Add to a <style> tag to prevent Juice from inlining its CSS and removing the tag. Useful for email client hacks.
    • data-juice-duplicates: Add to an element to override inlineDuplicateProperties. Use data-juice-duplicates (or "true") to enable duplicates, or data-juice-duplicates="false" to collapse to highest specificity.
    • data-juice-important: Add to an element to override preserveImportant. Use data-juice-important (or "true") to preserve !important, or data-juice-important="false" to strip it.
    <!-- keeps both background-color declarations, even if the option is off -->
    <div class="header" data-juice-duplicates></div>
    
    <!-- collapses to the highest-specificity declaration, even if the option is on -->
    <div class="header" data-juice-duplicates="false"></div>
    
    <style data-embed>
      u + .body .your-class-name {
        /* CSS here targets Gmail */
      }
    </style>
  3. Run Juice in the Browser

    master

    Because the default entry imports Node-only modules (fs, path), you cannot use the standard import in a browser environment.

    To use Juice in the browser, import from juice/client instead. This exposes:

    • juiceDocument
    • inlineDocument
    • inlineContent

    Note that juiceFile, juiceResources, and inlineExternal are not available in the browser client. Juice is ESM-only (v12+); modern bundlers like Vite, webpack 5, esbuild, Rollup, and Parcel 2+ will handle juice/client correctly. Browserify is not supported.

  4. Ignore CSS with comments

    master

    You can prevent Juice from inlining specific parts of your CSS using special comments:

    • Ignore entire file: Add /* juice ignore */ to the first line of a <style> block.
    • Ignore next rule: Add /* juice ignore next */ before a CSS rule.
    • Ignore next declaration: Add /* juice ignore next */ inside a CSS rule before a specific property.
    • Ignore blocks of code: Wrap multiple rules with /* juice start ignore */ and /* juice end ignore */.
    /* juice ignore next */
    h1 {
      color: blue;
    }
    
    .test {
      color: red;
      /* juice ignore next */
      font-weight: bold;
    }
  5. Configure Juice inlining options

    master

    All Juice methods accept an optional options object to control the inlining process. Common configuration properties include:

    • applyAttributesTableElements (default: true): Creates attributes for styles in juice.styleToAttribute on elements in juice.tableElements.
    • applyHeightAttributes (default: true): Uses CSS pixel heights to create height attributes on elements in juice.heightElements.
    • applyStyleTags (default: true): Inlines styles found in <style> tags.
    • applyWidthAttributes (default: true): Uses CSS pixel widths to create width attributes on elements in juice.widthElements.
    • decodeStyleAttributes (default: false): Decodes the value of style attributes.
    • extraCss (default: ""): Additional CSS to apply to the file.
    • inlineDuplicateProperties (default: false): If true, inlines all declarations with identical properties instead of only the highest specificity one.
    • insertPreservedExtraCss (default: true): Determines if preserved @media, @font-face, or keyframes from extraCss are inserted into the document. Can be a string (CSS/jQuery/cheerio selector) to specify where the <style> tag is appended.
    • inlinePseudoElements (default: false): Inserts ::before and ::after as <span> elements (modifies DOM).
    • preserveFontFaces (default: true): Preserves @font-face when removeStyleTags is true.
    • preserveImportant (default: false): Preserves !important in CSS values.
    • preserveMediaQueries (default: true): Preserves media queries when removeStyleTags is true.
    • preserveKeyFrames (default: true): Preserves keyframes when removeStyleTags is true.
    • preservePseudos (default: true): Preserves rules containing pseudo selectors defined in ignoredPseudos when removeStyleTags is true.
    • preservedSelectors (default: []): Array of CSS selectors (substring match) to preserve inside <style> tags when removeStyleTags or removeInlinedSelectors is true.
    • removeInlinedSelectors (default: false): Removes CSS rules from <style> tags after inlining (requires removeStyleTags: false).
    • removeStyleTags (default: true): Removes original <style> tags after inlining. Overrides removeInlinedSelectors.
    • resolveCSSVariables (default: true): Resolves CSS variables.
    • webResources (default: {}): Options passed to web-resource-inliner for remote resource fetching.
    • xmlMode (default: false): Outputs XML/XHTML with all tags closed (requires valid XML/XHTML input).
  6. Use Juice API methods

    master

    Juice provides several methods for inlining CSS depending on your input type and environment:

    • juice(html, [options]): Returns a string of HTML with inlined CSS. Does not fetch remote resources.
    • juice.juiceResources(html, options, callback): Fetches remote resources and returns inlined HTML via a callback callback(err, html).
    • juice.juiceFile(filePath, options, callback): Inlines CSS from a local file and fetches remote resources. Returns via callback(err, html).
    • juice.juiceDocument($, [options]): Performs in-place inlining on a cheerio instance. Returns the same instance. Does not fetch remote resources.
    • juice.inlineContent(html, css, [options]): Takes HTML and CSS strings and returns new HTML with the provided CSS inlined. Ignores <style> or <link> tags.
    • juice.inlineDocument($, css, [options]): Modifies a cheerio instance with the provided CSS string. Ignores <style> or <link> tags.
  7. Configure web resource handling with WebResourcesOptions

    master

    The webResources property in Options accepts a WebResourcesOptions object to control how external assets are processed:

    • images: Boolean or number (limit) for image inlining.
    • links: Boolean or number (limit) for link inlining.
    • scripts: Boolean or number (limit) for script inlining.
    • svgs: Boolean or number (limit) for SVG inlining.
    • inlineAttribute: The attribute name to use for inlined content.
    • rebaseRelativeTo: Path to rebase URLs against.
    • relativeTo: Path to make URLs relative to.
    • strict: Boolean for strict mode.
    • fileContent: String content for file resolution.
  8. Configure Juice global settings

    master

    You can modify the following global settings to change default behavior:

    • juice.codeBlocks: Object defining fenced code blocks to ignore (e.g., EJS, HBS). Use juice.codeBlocks.NAME = { start: '...', end: '...' } to add new ones.
    • juice.ignoredPseudos: Array of pseudo-selectors to ignore (default: ['hover', 'active', 'focus', 'visited', 'link']).
    • juice.widthElements: Array of HTML elements that can receive width attributes (default: ['TABLE', 'TD', 'TH', 'IMG']).
    • juice.heightElements: Array of HTML elements that can receive height attributes (default: ['TABLE', 'TD', 'TH', 'IMG']).
    • juice.styleToAttribute: Object mapping CSS properties to HTML attributes (e.g., {'background-color': 'bgcolor'}).
    • juice.tableElements: Array of table elements that can receive attributes from styleToAttribute (default: ['TABLE', 'TH', 'TR', 'TD', 'CAPTION', 'COLGROUP', 'COL', 'THEAD', 'TBODY', 'TFOOT']).
    • juice.nonVisualElements: Elements that will not have styles inlined (default: ['HEAD', 'TITLE', 'BASE', 'LINK', 'STYLE', 'META', 'SCRIPT', 'NOSCRIPT']).
    • juiceClient.excludedProperties: Array of CSS properties that won't be inlined.
  9. Use Juice CLI

    master

    Run Juice from the command line using the following syntax:

    juice [options] input.html output.html

    To use juice globally, install it via npm install juice -g.

    CLI Options: All standard Juice options are available using hyphen-delimited names (e.g., extraCss becomes --extra-css).

    Additional CLI-only options:

    • --css [filepath]: Loads and injects CSS into extraCss.
    • --options-file [filepath]: Loads options from a JSON file. CLI options take priority over file options.
    • codeBlocks can be included in the options file to support different template languages.
  10. Inline CSS in an HTML string using inlineExternal()

    master
    Use inlineExternal(html, inlineOptions, callback) to perform inlining using the underlying web-resource-inliner engine. This is useful for more complex resource inlining requirements. The inlineOptions object is merged with { fileContent: html }.
  11. Access Juice utilities and classes

    master

    The juice object exports several utility classes and helper functions for advanced configuration and manipulation:

    • juice.Selector: A utility for CSS selector handling.
    • juice.Property: A utility for CSS property handling.
    • juice.utils: The full suite of internal utility functions.
    • juice.version: The current version of the juice package.