一个用于 Vite 的插件,可自定义将 preload/prefetch 资源注入到 index.html
,支持 JS、CSS、图片等静态资源。
- 支持自定义哪些 chunk 需要插入
<link rel="preload">
或<link rel="prefetch">
- 支持自定义 link 的所有属性
- 支持插入到
<head>
或<body>
位置 - 支持 JS、CSS、图片等资源类型
npm install vite-plugin-custom-preload --save-dev
# 或
pnpm add vite-plugin-custom-preload -D
在 vite.config.ts
中引入并配置插件:
import customPreloadPlugin from 'vite-plugin-custom-preload';
export default {
plugins: [
customPreloadPlugin({
shouldPreload: (chunk) => {
// 只处理入口 JS、所有 CSS 和 png 图片
if (chunk.type === 'chunk' && chunk.fileName.endsWith('.js')) return true;
if (chunk.type === 'asset' && chunk.fileName.endsWith('.css')) return true;
if (chunk.type === 'asset' && chunk.fileName.endsWith('.png'))
return { as: 'image', type: 'image/png' };
return false;
},
rel: 'preload', // 或 'prefetch'
position: 'head', // 或 'body'
}),
],
};
选项 | 类型 | 说明 | 默认值 |
---|---|---|---|
shouldPreload | (chunk) => boolean | LinkAttributes | 控制每个 chunk 是否插入及插入属性,返回 true/false 或属性对象 | 入口 chunk |
rel | 'preload' | 'prefetch' | link 的 rel 属性 | preload |
position | 'head' | 'body' | 插入到 <head> 还是 <body>
|
head |
- 返回
false
:不插入 - 返回
true
:使用默认属性插入 - 返回属性对象:合并默认属性和自定义属性
ISC