相关推荐recommended
Vite处理html模板插件之vite-plugin-html
作者:mmseoamin日期:2023-12-02

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • 一、项目目录
  • 二、index.html
  • 三、vite.config.js
  • 四、打包dist的结果
  • 五、有个疑问

    前言

    背景:项目中需要使用模板html动态处理比如 icon 、title。我的项目里是需要在不同的打包指令下,打包的结果中index.html 中title 和 icon都不一致。之前的项目使用的是 html-webpack-plugin 插件。安装该插件的使用需要注意你项目的webpack版本,安装对应的版本插件。本次因为项目是vite项目,所以采用vite-plugin-html插件。本文作为使用记录。结尾还有个疑问一直没有解决,欢迎大神留言解答一下。


    提示:以下是本篇文章正文内容,下面案例可供参考

    一、项目目录

    项目目录如下,主要关注红框的 html文件

    Vite处理html模板插件之vite-plugin-html,在这里插入图片描述,第1张

    二、index.html

    Vite处理html模板插件之vite-plugin-html,在这里插入图片描述,第2张

    三、vite.config.js

    主要目的 是以template 值对应的 html 为模板,为其注入一些动态值。这里主要是 title、icon。

    import { createHtmlPlugin } from 'vite-plugin-html'
    
    export default defineConfig({
      plugins: [
        createHtmlPlugin({
            minify: true,
            pages: [
              {
                filename: 'index.html',
                template: 'index.html',
                injectOptions: {
                  data: {
                    title: product,
                    injectIcoLink: ``,
                    pubId: pubIdObj[product],
                  },
                },
              },
              {
                filename: '/legale/cookie/index.html',
                template: '/legal/cookie/index.html',
                injectOptions: {
                  data: {
                    title: product,
                    injectIcoLink: ``,
                    productName: product,
                  },
                },
              },
              {
                filename: '/legale/privacy/index.html',
                template: '/legal/privacy/index.html',
                injectOptions: {
                  data: {
                    title: product,
                    injectIcoLink: ``,
                    productName: product,
                  },
                },
              },
              {
                filename: '/legale/service/index.html',
                template: '/legal/service/index.html',
                injectOptions: {
                  data: {
                    title: product,
                    injectIcoLink: ``,
                    productName: product,
                  },
                },
              },
            ],
          })
      ]
    })
    

    四、打包dist的结果

    打包结果如预期,legal 整个文件夹都打到了dist 目录下,并且html 需要注入的值也都对应的注入进去了。

    Vite处理html模板插件之vite-plugin-html,在这里插入图片描述,第3张

    ``

    五、有个疑问

    本地环境打不开 legal里的html,结果如下。但是 postman 可以获取到 html 内容。 线上生产环境也是没有问题的,可以打开页面。 欢迎大佬给出建议

    Vite处理html模板插件之vite-plugin-html,在这里插入图片描述,第4张

    Vite处理html模板插件之vite-plugin-html,在这里插入图片描述,第5张