vite-plugin-virtual-mpa ⚡
Out-of-box MPA plugin for Vite 📦, with html template engine and virtual files support, generate multiple files using only one template.
English | 中文
Features
- 💡 EJS Template Capability
- 💡 Fully Typed APIs and Prompts, Tiny and Pretty.
- 🛠️ Customize the path of generated files, generate multiple files using only one template.
- 🛠️ MPA support & History Fallback API.
Usage
pnpm add -D vite-plugin-virtual-mpa
import { createMpaPlugin, createPages } from 'vite-plugin-virtual-mpa'
export default defineConfig({
plugins: [
createMpaPlugin({
pages: [
]
}),
],
})
const pages = createPages([
])
export default defineConfig({
plugins: [
createMpaPlugin({
pages,
}),
],
})
Motivation
When building MPA(multi-page-applications) with Vite, we usually need a plugin that:
-
Has a template engine such as EJS, which can use one template to generate multiple files, and can customize the path of the generated files at build time.
-
Auto configurations for rollupOptions.input
and provide the ability to configure the development server's proxy (primarily the History Fallback API).
There are so many MPA plugins for vite on the market, but it seems no one can do both of above at the same time. I filtered the following plugins based on name matching and downloads:
-
vite-plugin-mpa: It can automatically configure the entry and provide the DevServer proxy configuration (history fallback), but we must adjust the directory structure according to the convention, and does not support template engines and virtual entry, and cannot define the path to generate files.
-
vite-plugin-html-template: The author of this plugin is the same as vite-plugin-mpa, which is recommended by the author. It is primarily used in combination with the MPA plugin to provide template engine functionality, and also doesn't support virtual entry.
-
vite-plugin-html: It supports template engines only, but no virtual entry. You need to use multiple entry templates if you want to generate multiple files.
-
vite-plugin-virtual-html: It supports virtual entry points, provides a rendering interface to customize template engines. But there's no built-in template engine, so it's a bit cumbersome to use.
Here, "virtual entry" means that multiple entry HTML files are rendered through only one template file.
They have their strengths, but they don't work very well. Either it needs to be used in conjunction or it is a significant change to the existing project structure. Sometimes I wonder if it is losing the advantage of template by implementing a template engine but requiring multiple template files.
This plugin is designed to solve these problems, and it has all of these capabilities at the same time. By combining virtual entry and template engine, users can generate different entry HTML with only one template, and can customize the output path of the entry file (no need to manually write scripts to move!). It also provides an interface to configure rewrite rules for the development server, so that the development can correctly request the entry file.
If your project is using Vite workflow and is an MPA application, you may want to give this plugin a try. It doesn't limit the technology stack, it doesn't matter if you use Vue or React or any other technologies.
Options
type FilterPattern = string | RegExp | (string | RegExp)[]
interface WatchHandler {
(ctx: {
server: ViteDevServer,
file: string,
type: Event
reloadPages: (pages: Page[]) => void
}): void
}
interface MpaOptions {
verbose?: boolean,
template?: `${string}.html`,
rewrites?: Rewrite[],
watchOptions?: WatchHandler | {
include?: Exclude<FilterPattern, null>,
excluded?: Exclude<FilterPattern, null>,
events?: Event[],
handler: WatchHandler
},
pages: Array<{
name: string;
filename?: `${string}.html`;
template?: string;
entry?: string;
data?: Record<string, any>,
}>
}
Examples
Click here codesandbox for a quick preview!
import { normalizePath } from "vite";
import { createMpaPlugin } from "vite-plugin-virtual-mpa"
const base = "/sites/"
export default defineConfig({
base,
plugins: [
createMpaPlugin({
pages: [
{
name: "apple",
filename: "fruits/apple.html",
entry: "/src/fruits/apple/apple.js",
data: {
title: "This is Apple page"
}
},
{
name: "banana",
filename: "fruits/banana.html",
entry: "/src/fruits/banana/banana.js",
data: {
title: "This is Banana page"
}
},
{
name: "strawberries",
filename: "fruits/strawberries.html",
entry: "/src/fruits/strawberries/strawberries.js",
data: {
title: "This is Strawberries page"
}
}
],
rewrites: [
{
from: new RegExp(normalizePath(`/${base}/(apple|banana|strawberries)`)),
to: (ctx) => normalizePath(`/fruits/${ctx.match[1]}.html`),
}
],
}),
],
})
Default Rewrite Rules
As the examples above says 👆🏻, if you follow the conventions of configurations, this plugin will generate a default rule which looks like:
{
from: new RegExp(normalizePath(`/${base}/(${Object.keys(inputMap).join('|')})`)),
to: ctx => normalizePath(`/${inputMap[ctx.match[1]]}`),
}
Here, inputMap is a dictionary that map the name matched into the corresponding virtual entry file. The structure of the inputMap
is as follows:
{
apple: 'fruits/apple.html',
banana: 'fruits/banana.html',
strawberries: 'fruits/strawberries.html',
}
Request url /sites/apple/xxx
will be processed by Default Rewrite Rule, and will be redirected to the corresponding fallback url /fruits/apple.html
(name 'apple'
correspond to 'fruits/apple.html'
, the same goes for the rest ones), which is based on viteConfig.base(here is '/sites/')
. So the final url will be /sites/fruits/apple.html
.
About virtual entry files
Usually during development, our files are written locally, and we can access the local corresponding files through the URL through the DevServer proxy. The same is true for virtual files, except that the corresponding file is not written to the filesystem but is kept in memory.
The plugin generates virtual files using the template system, allowing you to reach the in-memory virtual files at development time and generate them in the corresponding directory at build time.
It's perfectly okay to think that these virtual files are really exist, and it will help you build an intuition about them in your mind to be able to write your proxy configuration correctly.
About EJS template engine
Except for the data
provided in the page configuration, ENV variables that start with 'VITE_'
will be auto injected into the provided template. More information about envprefix
can be found here.