npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

vite-plugin-webfont-dl

v3.10.3

Published

Vite plugin for downloading and injecting webfonts

Downloads

67,069

Readme

🔠 Webfont Dowload Vite plugin ⚡

NPM NPM downloads all-time NPM downloads last month

Collects webfont links, imports and definitions from your Vite project, downloads css and font files (privacy-first), add the fonts to your bundle (or serves through dev server), and injects font definitions using a non-render blocking method, meanwhile stores external css and font files in a persistent file cache, making them available for offline development.

📦 Install

npm i vite-plugin-webfont-dl -D

📖 Table of Contents

  1. 📦 Install
  2. Usage:
  3. 🚀 That's all!
  4. 🧩 Supported webfont providers
  5. 🛠️ Options
  6. Third-party webfonts
  7. 🔮 How it works
  8. 📊 Benchmark
  9. 📚 Resources
  10. 📄 License

😎 Usage: Zero config [method A]

Extracts, downloads and injects fonts from the original Google Fonts code snippet.

  1. Select your font families in your webfont provider (e.g. Google Fonts) and copy the code into <head> from the "Use on the web" block:
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Fira+Code:wght@300;400&family=Roboto:wght@100&display=swap" rel="stylesheet">
  2. Add webfontDownload to your Vite plugins without any configuration and the plugin automagically will take care of everything:
    // vite.config.js
    
    import webfontDownload from 'vite-plugin-webfont-dl';
    
    export default {
      plugins: [
        webfontDownload(),
      ],
    };
  3. The original webfont tags will be replaced in dist/index.html:
    <style>@font-face{font-family:...;src:url(/assets/foo-xxxxxxxx.woff2) format('woff2'),url(/assets/bar-yyyyyyyy.woff) format('woff')}...</style>

🦄 Usage: Simple config [method B]

Extracts, downloads and injects fonts from the configured webfont CSS URL(s).

  1. Select your font families in your webfont provider (e.g. Google Fonts) and copy the CSS URL(s) from the "Use on the web" code block:
    <link href="[CSS URL]" rel="stylesheet">
  2. Add webfontDownload to your Vite plugins with the selected Google Fonts CSS URL(s):
    // vite.config.js
    
    import webfontDownload from 'vite-plugin-webfont-dl';
    
    export default {
      plugins: [
        webfontDownload([
          'https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap',
          'https://fonts.googleapis.com/css2?family=Fira+Code&display=swap'
        ]),
      ],
    };

🚀 That's all!

The webfonts are injected and ready to use. The plugin does its job seamlessly whether you are working on local development server or building to production.

h1 {
  font-family: 'Press Start 2P', cursive;
}

h2 {
  font-family: 'Fira Code', monospace;
}

🔌 Laravel

To make it work with Laravel Vite Plugin add this line to your blade file:

@vite('webfonts.css')

📸 Screenshot

🧩 Supported webfont providers

🛠️ Options

  • injectAsStyleTag (boolean, default: true): Inject webfonts as <style> tag (embedded CSS) or as an external .css file

  • minifyCss (boolean, default: value of build.minify): Minify CSS code during build.

  • embedFonts (boolean, default: false): Embed base64-encoded fonts into css. In some cases can cause filesize increase if css containes multiple references to same font file. Example

  • async (boolean, default: true): Prevent the usage of inline event handlers (webfonts.css) that can cause Content Security Policy issues. Works only with injectAsStyleTag:false.

  • cache (boolean, default: true): Persistently store downloaded css and font files in local file cache. If set to false the existing cache will be deleted.

  • proxy (false|AxiosProxyConfig, default: false): Proxy configuration for network requests.

  • assetsSubfolder (string, default: ''): Moves downloaded font files to separate subfolder in assets directory.

usage:

ViteWebfontDownload(
  [],
  {
    injectAsStyleTag: true,
    minifyCss: true,
    embedFonts: false,
    async: true,
    cache: true,
    proxy: false,
    assetsSubfolder: '',
  }
)

or:

ViteWebfontDownload(
  [
    'https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap',
  ],
  {
    injectAsStyleTag: true,
    minifyCss: true,
    embedFonts: false,
    async: true,
    cache: true,
    proxy: false,
    assetsSubfolder: '',
  }
)

❓ Third-party webfonts

⚠️ Using the standard method to add third-party webfonts (Google Fonts, Bunny Fonts or Fontshare) to a webpage can slow down page load significantly. Lighthouse and PageSpeed Insights calls them "render-blocking resource", which means the page can't render fully until the webfonts CSS hasn't been fetched from the remote server.

📈 By avoiding render-blocking resources caused by third-party webfonts, you can boost page performance which leads to better user-experience and it improves SEO results.

⚙️ The plugin downloads the given fonts from the third-party webfont service (like Google Fonts) and dynamically injects them (as an internal or external stylesheet) into your Vite project, transforming the third-party webfonts into self-hosted ones. 🤩

🔐 In addition to the significant performance increase, your visitors will also benefit to privacy protection, since there is no third-party server involved.

🔮 How it works

📉 Google Fonts

Google Fonts generates the following code which you have to inject into your website's <head>, example:

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Fira+Code&display=swap" rel="stylesheet">

📱 What happens on client-side with Google Fonts:

  1. First line gives a hint to the browser to begin the connection handshake (DNS, TCP, TLS) with fonts.googleapis.com. This happens in the background to improve performance. [preconnect]
  2. Second line is another preconnect hint to fonts.gstatic.com. [preconnect]
  3. Third line instructs the browser to load and use a CSS stylesheet file from fonts.googleapis.com (with font-display:swap). [stylesheet]
  4. The browser downloads the CSS file and starts to parse it. The parsed CSS is a set of @font-face definitions containing font URLs from fonts.gstatic.com server.
  5. The browser starts to download the all relevant fonts from fonts.gstatic.com.
  6. After the successful fonts download the browser swaps the fallback fonts to the downloaded ones.

🆚

📈 Webfont-DL Vite plugin

On the contrary, Webfont-DL plugin does most of the job at build time, leaves the minimum to the browser.

Webfont-DL plugin

  • collects the webfont CSS URLs (from plugin config, index.html and the generated CSS)
  • downloads the webfont CSS file(s)
  • extracts the font URLs
  • downloads the fonts
  • adds the fonts to the bundle
  • generates an embedded CSS (<style> tag) or a webfont / external CSS file
  • add them to the bundle and injects the following code into your website's <head> using a non-render blocking method, example:
<style>
  @font-face {
    font-family: 'Fira Code';
    font-style: normal;
    font-weight: 300;
    font-display: swap;
    src: url(/assets/uU9eCBsR6Z2vfE9aq3bL0fxyUs4tcw4W_GNsJV37Nv7g.9c348768.woff2) format('woff2');
    unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
  }
  ...
</style>

or (using dev server or injectAsStyleTag: false option)

<link rel="preload" as="style" href="/assets/webfonts.b904bd45.css">
<link rel="stylesheet" media="print" onload="this.onload=null;this.removeAttribute('media');" href="/assets/webfonts.b904bd45.css">

📱 What happens on client-side with Webfont-DL plugin:

  1. Load fonts from the embedded CSS (<style> tag).

or

  1. First line instructs the browser to prefetch a CSS file for later use as stylesheet. [preload]
  2. Second line instructs the browser to load and use that CSS file as a "print" stylesheet (non-render blocking). After loading it promote to "all" media type stylesheet (by removing the "media" attribute). [stylesheet]

📊 Benchmark

Starter Vite project with

| ▶️ Standard Google Fonts | 🆚 | ▶️ Webfont DL Vite plugin | |:---:|:---:|:---:| | 🔗 webfont.feat.agency | | 🔗 webfont-dl.feat.agency |

Compare

📚 Resources

📄 License

MIT License © 2022 feat.