vite-plugin-html
功能
- HTML 壓縮能力
- EJS 模版能力
- 多頁應(yīng)用支持
- 支持自定義
entry
- 支持自定義
template
安裝 (yarn or npm)
node version: >=12.0.0
vite version: >=2.0.0
yarn add vite-plugin-html -D
或
npm i vite-plugin-html -D
使用
- 在
index.html
中增加 EJS 標(biāo)簽雪标,例如
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title><%- title %></title>
<%- injectScript %>
</head>
- 在
vite.config.ts
中配置,該方式可以按需引入需要的功能即可
import { defineConfig, Plugin } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createHtmlPlugin } from 'vite-plugin-html'
export default defineConfig({
plugins: [
vue(),
createHtmlPlugin({
minify: true,
/**
* 在這里寫entry后,你將不需要在`index.html`內(nèi)添加 script 標(biāo)簽,原有標(biāo)簽需要?jiǎng)h除
* @default src/main.ts
*/
entry: 'src/main.ts',
/**
* 如果你想將 `index.html`存放在指定文件夾震放,可以修改它,否則不需要配置
* @default index.html
*/
template: 'public/index.html',
/**
* 需要注入 index.html ejs 模版的數(shù)據(jù)
*/
inject: {
data: {
title: 'index',
injectScript: `<script src="./inject.js"></script>`,
},
},
}),
],
})
多頁應(yīng)用配置
import { defineConfig } from 'vite'
import { createHtmlPlugin } from 'vite-plugin-html'
export default defineConfig({
plugins: [
createHtmlPlugin({
minify: true,
pages: [
{
entry: 'src/main.ts',
filename: 'index.html',
template: 'public/index.html',
injectOptions: {
data: {
title: 'index',
injectScript: `<script src="./inject.js"></script>`,
},
},
},
{
entry: 'src/other-main.ts',
filename: 'other.html',
template: 'public/other.html',
injectOptions: {
data: {
title: 'other page',
injectScript: `<script src="./inject.js"></script>`,
},
},
},
],
}),
],
})
參數(shù)說明
createHtmlPlugin(options: UserOptions)
UserOptions
參數(shù) | 類型 | 默認(rèn)值 | 說明 |
---|---|---|---|
entry | string |
src/main.ts |
入口文件 |
template | string |
index.html |
模板的相對路徑 |
inject | InjectOptions |
- | 注入 HTML 的數(shù)據(jù) |
minify | boolean|MinifyOptions |
- | 是否壓縮 html |
pages | PageOption |
- | 多頁配置 |
InjectOptions
參數(shù) | 類型 | 默認(rèn)值 | 說明 |
---|---|---|---|
data | Record<string, any> |
- | 注入的數(shù)據(jù) |
ejsOptions | EJSOptions |
- | ejs 配置項(xiàng)EJSOptions |
data
可以在 html
中使用 ejs
模版語法獲取
env 注入
默認(rèn)會(huì)向 index.html 注入 .env
文件的內(nèi)容,類似 vite 的 loadEnv
函數(shù)
PageOption
參數(shù) | 類型 | 默認(rèn)值 | 說明 |
---|---|---|---|
filename | string |
- | html 文件名 |
template | string |
index.html |
模板的相對路徑 |
entry | string |
src/main.ts |
入口文件 |
injectOptions | InjectOptions |
- | 注入 HTML 的數(shù)據(jù) |
MinifyOptions
默認(rèn)壓縮配置
collapseWhitespace: true,
keepClosingSlash: true,
removeComments: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
useShortDoctype: true,
minifyCSS: true,
運(yùn)行示例
pnpm install
# spa
cd ./packages/playground/basic
pnpm run dev
# map
cd ./packages/playground/mpa
pnpm run dev