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:[] };
    }}
  };
}
相关推荐
CrabXin3 小时前
前端如何用 CDN 加速网站性能全解析
前端
beckyyy3 小时前
WebSSH的简单实现
前端·ssh
GISer_Jing3 小时前
透过浏览器原理学习前端三剑客:HTML、CSS与JavaScript
前端·javascript·css·html
长空任鸟飞_阿康3 小时前
提示词管理器设计:从需求到用户体验的高效落地逻辑
前端·人工智能·ux
零點壹度ideality3 小时前
鸿蒙实现可以上下左右滑动的表格-摆脱大量ListScroller
前端·harmonyos
林希_Rachel_傻希希3 小时前
this 的指向与 bind() 方法详解
前端·javascript
Komorebi゛3 小时前
【Vue3】使用websocket实现前后端实时更新数据
前端·websocket
想要狠赚笔的小燕3 小时前
老项目救星:Vue3/Vite/JS 项目渐进式引入「代码 + Commit」自动化规范全指南(多人协作)
前端·vue.js
用户352120195603 小时前
React-router v7(下)
前端
枫,为落叶3 小时前
【vue】设置时间格式
前端·javascript·vue.js