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:[] };
    }}
  };
}
相关推荐
阿懂在掘金10 小时前
企业级命令式弹窗方案:三行代码适配已有 Dialog
前端·vue.js·前端框架
Revolution6110 小时前
测试接口为什么进了生产包:前端环境变量到底在什么时候生效
前端·前端工程化
午安~婉10 小时前
Git中SSH连接
前端·git·gitee
盏灯10 小时前
mac 外接磁盘,热更新失效
前端·后端
那些年丶ny10 小时前
颜色扩展库
前端·javascript·数据可视化
ihuyigui10 小时前
海外签收通知短信接口
android·java·开发语言·前端·数据库·后端
YWL10 小时前
OpenLayers + Vue 2 使用指南(01)
前端·javascript·vue.js
暖和_白开水11 小时前
数据分析agent (七):contextvars 模块上下文request_id
java·前端·数据分析
程序员黑豆11 小时前
鸿蒙应用开发:Flex 组件从入门到实战
前端·华为·harmonyos
大爱编程♡11 小时前
Vue3+TypeScript+element-plus的文章管理项目(配后端接口)-退出及文章管理页面
前端·javascript·typescript