font-spider

repository·master·Indexed 26 days ago

https://github.com/aui/font-spider

A smart webfont compression and format conversion tool (version 1.3.5) that analyzes HTML and CSS files to identify used characters and generate optimized font subsets. It supports woff2, woff, eot, and svg formats, provided a .ttf source is available. It can be used via a CLI or as a Node.js module with spider() and compressor() functions. Limitations include support only for utf-8 encoding and static content, as JavaScript-inserted styles and content are not detected.

Tokens
3.3K
Snippets
8
Records
21
Agent score
87%

What's inside font-spider

  1. Compress WebFonts using the font-spider CLI

    master

    To compress WebFonts, you must first ensure your CSS @font-face rules reference an existing .ttf file. Font-spider will analyze your HTML and CSS files to identify used characters and then automatically generate compressed versions in woff2, woff, eot, and svg formats.

    Step 1: Prepare your CSS

    Ensure your @font-face declaration includes a path to a .ttf file:

    @font-face {
      font-family: 'source';
      src: url('../font/source.eot');
      src:
        url('../font/source.eot?#font-spider') format('embedded-opentype'),
        url('../font/source.woff2') format('woff2'),
        url('../font/source.woff') format('woff'),
        url('../font/source.ttf') format('truetype'),
        url('../font/source.svg') format('svg');
      font-weight: normal;
      font-style: normal;
    }
    
    .home h1, .demo > .test {
        font-family: 'source';
    }

    Step 2: Run the CLI

    Run the command followed by the HTML files you want to analyze:

    font-spider [options] <htmlFile1 htmlFile2 ...>
    font-spider dest/news.html dest/index.html dest/about.html
  2. Prepare CSS for WebFont compression

    master

    To use font-spider, your CSS must include an @font-face declaration.

    Requirement: The src attribute within @font-face must include a path to an existing .ttf file. Font-spider will automatically generate the other formats (e.g., .eot, .woff, .svg) based on the .ttf source.

    /* Example CSS setup */
    @font-face {
      font-family: 'pinghei';
      src: url('../font/pinghei.eot');
      src:
        url('../font/pinghei.eot?#font-spider') format('embedded-opentype'),
        url('../font/pinghei.woff') format('woff'),
        url('../font/pinghei.ttf') format('truetype'),
        url('../font/pinghei.svg') format('svg');
      font-weight: normal;
      font-style: normal;
    }
    
    /* Apply the font to elements */
    .home h1, .demo > .test {
        font-family: 'pinghei';
    }
  3. Configure font-spider options

    master

    The following options can be passed to spider() or compressor() to control behavior:

    OptionTypeDescription
    ignoreArray<String>Rules (regex supported) to ignore loaded files. Mutually exclusive with resourceIgnore.
    mapArray<Array<String>>Mapping rules (regex supported) to map remote font files to local paths. Mutually exclusive with resourceMap. Example: [['http://font-spider.org/font', __dirname + '/font']].
    backupBooleanWhether to backup the original font files. Default: true.
    uniqueBooleanWhether to deduplicate the found text. Default: true.
    sortBooleanWhether to sort the found text. Default: true.
    debugBooleanWhether to enable debug mode. Default: false.
    loadCssFileBooleanWhether to support loading external CSS files. Default: true.
    silentBooleanWhether to ignore internal parsing errors. Set to false for debugging. Default: true.
    resourceTimeoutNumberRequest timeout limit in milliseconds. Default: 8000.
    resourceMaxNumberNumberMaximum number of files to load. Default: 64.
    resourceCacheBooleanWhether to cache successfully requested resources. Default: true.
    resourceMapFunction(file) -> StringMaps resource paths. Mutually exclusive with map.
    resourceIgnoreFunction(file) -> BooleanIgnores resources. Mutually exclusive with ignore.
    resourceBeforeLoadFunction(file)Event triggered before a resource is loaded.
    resourceRequestHeadersFunction(file) -> ObjectReturns custom request headers for remote resources.
  4. Understand font-spider limitations

    master

    Before using font-spider, be aware of the following constraints:

    • Dynamic Content: Only constant texts and styles are supported. Content or styles inserted via JavaScript are not detected.
    • Font Formats: .otf files must be converted to .ttf format before starting the compression process.
    • Encoding: Only HTML and CSS files encoded in utf-8 are supported.
  5. Debug font processing issues

    master

    If font processing is inaccurate, it may be due to CSS loading or parsing errors being ignored. To debug, set silent: false and debug: true in your options object.

    // Use these settings to debug
    {
        silent: false,
        debug: true
    }
  6. Full workflow example: Spider and Compress fonts

    master

    This example demonstrates the complete workflow: scanning an HTML file for font usage and then compressing the resulting fonts while keeping backups.

    var fontSpider = require('font-spider');
    
    fontSpider.spider([__dirname + '/index.html'], {
        silent: false
    }).then(function(webFonts) {
        return fontSpider.compressor(webFonts, {backup: true});
    }).then(function(webFonts) {
        console.log(webFonts);
    }).catch(function(errors) {
        console.error(errors);
    });
    var fontSpider = require('font-spider');
    
    fontSpider.spider([__dirname + '/index.html'], {
        silent: false
    }).then(function(webFonts) {
        return fontSpider.compressor(webFonts, {backup: true});
    }).then(function(webFonts) {
        console.log(webFonts);
    }).catch(function(errors) {
        console.error(errors);
    });
  7. Use fontSpider.spider() to query WebFonts

    master

    Use fontSpider.spider() to scan HTML files and retrieve WebFont description information.

    Parameters:

    • htmlFiles (Array<String>): A list of paths to the HTML files to be scanned.
    • options (Object): Configuration options for the spidering process.
    • callback (Function, optional): A callback function that receives the WebFonts description information. If omitted, the method returns a Promise.
    /**
     * @param   {Array<String>}     网页路径列表
     * @param   {Object}            选项
     * @param   {Function}          回调函数。接收 `WebFonts` 描述信息
     * @return  {Promise}           如果没有 `callback` 参数则返回 `Promise` 对象
     */
    fontSpider.spider(htmlFiles, options, callback)
  8. Use fontSpider.compressor() to compress fonts

    master

    Use fontSpider.compressor() to process font files based on provided WebFont description information.

    Parameters:

    • webFonts (Array<WebFont>): The WebFont description information (usually obtained from fontSpider.spider()).
    • options (Object): Configuration options for the compression process.
    • callback (Function, optional): A callback function that receives the WebFonts description information. If omitted, the method returns a Promise.
    /**
     * @param   {Array<WebFont>}    `WebFonts` 描述信息
     * @param   {Object}            选项
     * @param   {Function}          回调函数。接收 `WebFonts` 描述信息
     * @return  {Promise}           如果没有 `callback` 参数则返回 `Promise` 对象
     */
    fontSpider.compressor(webFonts, options, callback)
  9. Configure compression options

    master

    The compression process can be configured via an options object (passed as the adapter argument).

    One primary configuration key is:

    • backup: A boolean that determines whether the original font files are backed up before compression.

    Compress.defaults sets backup: true by default.

  10. Font-spider limitations

    master

    Be aware of the following constraints when using font-spider:

    • Dynamic Content: Only supports static text and styles. Elements or styles inserted via JavaScript are not supported.
    • Font Formats: OpenType font support is incomplete.
    • Encoding: Only supports utf-8 encoded HTML and CSS.
    • CSS Content Property: The content property in CSS is only supported for plain text; it does not support functions like counter() or other advanced features.