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:[] };
    }}
  };
}
相关推荐
知识分享小能手15 分钟前
Bootstrap 5学习教程,从入门到精通,Bootstrap 5 表单验证语法知识点及案例代码(34)
前端·javascript·学习·typescript·bootstrap·html·css3
一只小灿灿29 分钟前
前端计算机视觉:使用 OpenCV.js 在浏览器中实现图像处理
前端·opencv·计算机视觉
前端小趴菜0541 分钟前
react状态管理库 - zustand
前端·react.js·前端框架
Jerry Lau1 小时前
go go go 出发咯 - go web开发入门系列(二) Gin 框架实战指南
前端·golang·gin
我命由我123452 小时前
前端开发问题:SyntaxError: “undefined“ is not valid JSON
开发语言·前端·javascript·vue.js·json·ecmascript·js
0wioiw02 小时前
Flutter基础(前端教程③-跳转)
前端·flutter
落笔画忧愁e2 小时前
扣子Coze纯前端部署多Agents
前端
海天胜景2 小时前
vue3 当前页面方法暴露
前端·javascript·vue.js
GISer_Jing2 小时前
前端面试常考题目详解
前端·javascript
Boilermaker19923 小时前
【Java EE】SpringIoC
前端·数据库·spring