Vite plugin for injecting html, js, css code snippets into index.html
npm install vite-plugin-html-injectionindex.html 中注入 HTML、JS 和 CSS 代码片段的 Vite 插件。
index.html 文件中 - 例如,您可能需要包含 Google Analytics 的代码、PWA 服务工作者、Open Graph 和 Twitter Card 元数据、启动画面、客户支持小部件等。
index.html 变得臃肿且难以管理。
index.html 干净整洁,并在构建时注入它们。无需在 index.html 中添加特殊的占位符标签。
buildModes 属性,您可以根据环境启用或禁用特定的代码片段,简化开发并在 dev 模式下禁用不必要的代码。
类型 - raw、js 和 css。raw 片段按原样注入,而 js 和 css 片段分别被包装在 和 标签中。默认类型值为 raw。
index.html 中注入代码片段:
标签的开头(head-prepend)
标签的结尾(head)
标签的开头(body-prepend)
标签的结尾(body)
injectTo 值为:head-prepend、head、body-prepend 和 body。
bash
pnpm add vite-plugin-html-injection -D
`
`bash
yarn add vite-plugin-html-injection -D
`
`bash
npm i vite-plugin-html-injection -D
`
使用
1. 在 Vite 插件中添加 vite-plugin-html-injection,并进行必要的配置:
`js
// vite.config.js
import { defineConfig } from "vite";
import { htmlInjectionPlugin } from "vite-plugin-html-injection";
export default defineConfig({
plugins: [
htmlInjectionPlugin({
// 转换顺序 - 设置为 "pre" 以在 HTML 文件中使用环境变量替换
// 详见 https://vite.dev/guide/api-plugin.html#transformindexhtml
order: "pre",
// 示例注入
injections: [
{
// (可选)注入名称
name: "Open Graph",
// 相对于 Vite 项目根目录的代码片段文件路径
path: "./src/injections/open-graph.html",
// (可选)代码片段类型:raw | js | css
type: "raw",
// 注入位置:head | body | head-prepend | body-prepend
injectTo: "head",
// (可选)适用的模式:dev | prod | both
buildModes: "both",
},
{
name: "Google analytics",
path: "./src/injections/ga.html",
type: "raw",
injectTo: "body",
buildModes: "prod",
},
],
}),
],
});
`
> #### 提示:
>
> 您可以将配置对象放在单独的 JSON 文件中,并在 vite.config.js 中导入它
2. 创建相应的代码片段:
`html
`
`html
`
就是这样。执行 npm serve 或 npm build 命令后,代码片段将被注入。
签名
该插件是强类型的。以下是其配置的签名:
`ts
export interface IHtmlInjectionConfig {
injections: IHtmlInjectionConfigInjection[];
order?: "pre" | "post";
}
export interface IHtmlInjectionConfigInjection {
name?: string;
path: string;
type?: "raw" | "js" | "css"; // 默认为 'raw'
injectTo: "head" | "body" | "head-prepend" | "body-prepend";
buildModes?: "dev" | "prod" | "both"; // 默认为 'both'
}
``