Home

Awesome

This package will not receive anymore update. You can switch to unplugin-inject-preload.

npm node-current Coverage Status

vite-plugin-inject-preload

A Vite plugin for injecting <link rel='preload'>

This plugin adds preload links on build by getting ViteJS output assets.

Supporting Vite 3 and 4.

Currently, this plugin only works on build because of the way Vite behave.

📦 Install

npm i -D vite-plugin-inject-preload

# yarn
yarn add -D vite-plugin-inject-preload

# pnpm
pnpm add -D vite-plugin-inject-preload

👨‍💻 Usage

All the files needs to be process by ViteJS to be find by the plugin. For example, if I load this CSS file :

@font-face {
  font-family: 'Roboto';
  src: url('./../fonts/Roboto-Italic.woff2');
  font-weight: 400;
  font-style: italic;
}

@font-face {
  font-family: 'Roboto';
  src: url('./../fonts/Roboto-Regular.woff2');
  font-weight: 400;
  font-style: normal;
}

I can make the following configuration for VitePluginInjectPreload :

// vite.config.js / vite.config.ts
import VitePluginInjectPreload from 'vite-plugin-inject-preload'

export default {
  plugins: [
    VitePluginInjectPreload({
      files: [
        {
          match: /Roboto-[a-zA-Z]*-[a-z-0-9]*\.woff2$/
        },
        {
          match: /lazy.[a-z-0-9]*.(css|js)$/,
        }
      ]
    })
  ]
}

For the full example, check the demo folder available here.

Options

With the full options usage, you can do something like this :

// vite.config.js / vite.config.ts
import VitePluginInjectPreload from 'vite-plugin-inject-preload'

export default {
  plugins: [
    VitePluginInjectPreload({
      files: [
        {
          match: /Roboto-[a-zA-Z]*-[a-z-0-9]*\.woff2$/,
          attributes: {
            'type': 'font/woff2',
            'as': 'font',
            'crossorigin': 'anonymous',
            'data-font': 'Roboto'
          }
        },
        {
          match: /lazy.[a-z-0-9]*.(js)$/,
          attributes: {
            rel: 'modulepreload',
            type: undefined,
          }
        }
      ],
      injectTo: 'head-prepend'
    })
  ]
}

👨‍💼 Licence

GPL-3.0