vite 实现多页面打包,html模板插槽自动引入插件

前端项目开发中,多页面打包是常见需求,vite 原生支持多页面打包,但需要手动配置,本文介绍如何使用vite 实现多页面打包。 静态html并没有相互引用的功能,很多情况下,html界面的页首页脚是相同的。每个页面都引用相同的html代码,太冗余了,也不方便修改。下面基于viet插件,实现html模板插槽自动引入模板文件功能。 借鉴参考:blog.csdn.net/warmbook/ar...

vite 实现多页面打包

vite.config.js

配置多页面入口,与自定义的html模板插件

js 复制代码
import { defineConfig } from 'vite';
import { resolve } from 'path';
import myHtmlTemplatePlugin from './plugins/htmlTemplate';

export default defineConfig({
  plugins: [myHtmlTemplatePlugin()],
  build: {
    rollupOptions: {
      input: {
        index:resolve(__dirname, 'pages/index.html'),
        about:resolve(__dirname, 'pages/about.html')
      },
    },
  },
});

html 模板

index.html, about.html

js 复制代码
// 通用html 省略

//about.html
<div>about</div>
<script type="module" src="/src/about.ts"></script>

//index.html
<include src="./components/header.html"></include>
<div>index</div>
<include src="./components/footer.html"></include>
<script type="module" src="/src/index.ts"></script>

js文件

src/index.ts, src/about.ts

js 复制代码
//about.ts
import './style.css'
console.log('Hello Vite!','about.ts')

//index.ts
import './style.css'
console.log('Hello Vite!','index.ts')

打包

npm run build

js 复制代码
dist
├── assets
│   ├── 
│─ about.html
│─ index.html

htmlTemplate 插件,处理html插槽

在build/dev时处理html模板里的插槽数据,把插槽替换为对应的html文件。 plugins/htmlTemplate.ts

js 复制代码
import { Plugin } from 'vite';
import fs from 'fs'
import { dirname, join } from 'path'

function compressHTML(html) {
  // 去除注释
  html = html.replace(/<!--[\s\S]*?-->/g, "");
  // 去除多余空白
  html = html.replace(/\s+/g, " ");
  // 去除标签之间空格
  html = html.replace(/>\s+</g, "><");
  return html.trim();
}

export default function myHtmlTemplatePlugin(): Plugin {
  return {
    name: 'my-html-template-plugin',
    // vite特有钩子,填充html文件插槽
    transformIndexHtml:{
      enforce:'pre',
      async transform(html, ctx) {
        const directory = dirname(ctx.filename);
        html = html.replace(/\<include.*src="(.*)">.*\<\/include\>/gi, (match, p1, offset, string) => {
          const filePath = join(directory, p1);
          let inc_data = fs.readFileSync(filePath, 'utf8');
          return inc_data;
        });
        html = compressHTML(html);
        return { html, tags:[] };
    }}
  };
}
相关推荐
阿珊和她的猫1 小时前
`require` 与 `import` 的区别剖析
前端·webpack
谎言西西里1 小时前
零基础 Coze + 前端 Vue3 边玩边开发:宠物冰球运动员生成器
前端·coze
努力的小郑2 小时前
2025年度总结:当我在 Cursor 里敲下 Tab 的那一刻,我知道时代变了
前端·后端·ai编程
GIS之路2 小时前
GDAL 实现数据空间查询
前端
OEC小胖胖2 小时前
01|从 Monorepo 到发布产物:React 仓库全景与构建链路
前端·react.js·前端框架
2501_944711433 小时前
构建 React Todo 应用:组件通信与状态管理的最佳实践
前端·javascript·react.js
困惑阿三3 小时前
2025 前端技术全景图:从“夯”到“拉”排行榜
前端·javascript·程序人生·react.js·vue·学习方法
苏瞳儿3 小时前
vue2与vue3的区别
前端·javascript·vue.js
weibkreuz4 小时前
收集表单数据@10
开发语言·前端·javascript
hboot5 小时前
别再被 TS 类型冲突折磨了!一文搞懂类型合并规则
前端·typescript