vite-plugin-html的使用及实现

简介: 【8月更文挑战第4天】vite-plugin-html的使用及实现(实现一个简易版的插件)

vite-plugin-html

https://github.com/vbenjs/vite-plugin-html

插件作用

  • HTML 压缩能力
  • EJS模板能力
  • 多页面应用支持
  • 支持定制entry
  • 支持定制index.html的模板内容

    安装

    yarn add vite-plugin-html -D
    

    npm i vite-plugin-html -D
    

    用法

  • 添加 EJS 标签index.html,例如

    <head>
    <meta charset="UTF-8" />
    <link rel="icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title><%- title %></title>
    <%- injectScript %>
    </head>
    

    配置vite.config.ts,根据需要引入需要的功能
    ```javascript
    import { defineConfig, Plugin } from 'vite'
    import vue from '@vitejs/plugin-vue'

import { createHtmlPlugin } from 'vite-plugin-html'

export default defineConfig({
plugins: [
vue(),
createHtmlPlugin({
// 是否压缩html
minify: true,
//在这里写完条目后,你不需要在' index.html '中添加脚本标签,原来的标签需要删除
entry: 'src/main.ts',
//更改index.html位置
template: 'public/index.html',
//需要注入index.html ejs模板的数据
inject: {
data: {
title: '自定义网站标题',
injectScript: <script src="./inject.js"></script>,
},
},
}),
],
})

基础配置表说明

| 参数名 | 类型 | 默认值 | 描述 |
| --- | --- | --- | --- |
| entry | string | src/main.ts | 入口文件路径 |
| template | string | index.html | index.html模板路劲 |
| inject | InjectOptions | - | 需要注入index.html的数值 |
| minify | boolean|MinifyOptions | - | 是否压缩html |

这个插件需要更改index.hmtl模板,因此,我们需要了解transformIndexHtml钩子
## transformIndexHtml

- **类型:** IndexHtmlTransformHook | { enforce?: 'pre' | 'post', transform: IndexHtmlTransformHook }
- **种类:** 转换 index.html 的专用钩子。钩子接收当前的 HTML 字符串和转换上下文。上下文在开发期间暴露[ViteDevServer](https://vitejs.cn/vite3-cn/guide/api-javascript.html#vitedevserver)实例,在构建期间暴露 Rollup 输出的包。这个钩子可以是异步的,并且可以返回以下其中之一:
   - 经过转换的 HTML 字符串
   - 注入到现有 HTML 中的标签描述符对象数组({ tag, attrs, children })。每个标签也可以指定它应该被注入到哪里(默认是在 <head> 之前)
   - 一个包含 { html, tags } 的对象

基础示例:
```javascript
const htmlPlugin = () => {
  return {
    name: 'html-transform',
    transformIndexHtml(html) {
      return html.replace(
        /<title>(.*?)<\/title>/,
        `<title>Title replaced!</title>`
      )
    }
  }
}

完整钩子签名:

type IndexHtmlTransformHook = (
  html: string,
  ctx: {
   
    path: string
    filename: string
    server?: ViteDevServer
    bundle?: import('rollup').OutputBundle
    chunk?: import('rollup').OutputChunk
  }
) =>
  | IndexHtmlTransformResult
  | void
  | Promise<IndexHtmlTransformResult | void>

type IndexHtmlTransformResult =
  | string
  | HtmlTagDescriptor[]
  | {
   
      html: string
      tags: HtmlTagDescriptor[]
    }

interface HtmlTagDescriptor {
   
  tag: string
  attrs?: Record<string, string>
  children?: string | HtmlTagDescriptor[]
  /**
   * 默认: 'head-prepend'
   */
  injectTo?: 'head' | 'body' | 'head-prepend' | 'body-prepend'
}

简易版实现

module.exports = (options) => {
   
  return {
   
    // 转换html的

    transformIndexHtml: {
   
      // 将我们插件的一个执行时机提前
      enforce: "pre",
      transform: (html, ctx) => {
   
        return html.replace(/<%= title %>/g, options.inject.data.title);
      }
    }
  };
};

这里的html就是模板内的html内容字符串
此时,项目内即可使用
index.html模板内

<title><%= title %></title>

vite.config.js中

// vite.config.js
import CreateHtmlPlugin from "./plugin/CreateHtmlPlugin";
import {
    defineConfig } from "vite";
export default defineConfig({
   
  plugins: [
    CreateHtmlPlugin({
   
      inject: {
   
        data: {
   
          title: "好好学习,天天向上"
        }
      }
    })
  ]
});
相关文章
nuxt3:vue-dompurify-html
nuxt3:vue-dompurify-html
392 0
|
前端开发 JavaScript
nuxt项目:css相关插件加载顺序问题【extract-css-chunks-webpack-plugin】
nuxt项目:css相关插件加载顺序问题【extract-css-chunks-webpack-plugin】
240 0
|
17天前
|
移动开发 Java API
HTML 插件详解
HTML中的插件如Flash、Java applets和ActiveX控件曾广泛用于扩展网页功能,但因安全性问题和跨浏览器兼容性不佳而逐渐被淘汰。现代替代方案包括HTML5的`&lt;audio&gt;`、`&lt;video&gt;`、`&lt;canvas&gt;`和SVG等,以及WebAssembly和各种JavaScript API(如WebRTC和WebGL),这些新技术不仅提升了网页性能和安全性,还改善了用户体验。建议开发者优先采用HTML5和相关API。
|
2月前
|
JavaScript 算法 前端开发
学习 node.js 六 Markdown 转为 html,zlib
【8月更文挑战第19天】
20 0
|
移动开发 弹性计算 前端开发
Html5和Webpack2:Webpack5打包JS和样式表
本实验将介绍通过Webpack5的打包JavaScript脚本和样式表
|
移动开发 JavaScript 前端开发
[HTML CSS JS ES6 JS WebAPI JQuery]学习笔记目录
[HTML CSS JS ES6 JS WebAPI JQuery]学习笔记目录
|
JavaScript
html使用vue模板、html引入vue.js-测试demo
html使用vue模板、html引入vue.js-测试demo
|
前端开发 JavaScript
Webpack的基本使用,将html和css文件打包
Webpack的基本使用,将html和css文件打包
|
存储 前端开发 JavaScript
配置 html-webpack-plugin 插件|学习笔记
快速学习配置 html-webpack-plugin 插件
182 0
配置 html-webpack-plugin 插件|学习笔记
|
JavaScript
Vue课程11-介绍html-webpack-plugin打包原理
Vue课程11-介绍html-webpack-plugin打包原理
143 0
Vue课程11-介绍html-webpack-plugin打包原理