refactor: add vite-plugin-html. Delete updateHtml related logic

This commit is contained in:
vben
2020-10-27 21:21:14 +08:00
parent 7bd0b8eb6f
commit 173d402162
19 changed files with 224 additions and 286 deletions

View File

@@ -4,15 +4,15 @@ import { sh } from 'tasksfile';
import { argv } from 'yargs';
import { runBuildConfig } from './buildConf';
import { runUpdateHtml } from './updateHtml';
// import { runUpdateHtml } from './updateHtml';
import { errorConsole, successConsole } from '../utils';
import { startGzipStyle } from '../plugin/gzip/compress';
import { startGzipStyle } from '../vite/plugin/gzip/compress';
export const runBuild = async (preview = false) => {
try {
const argvList = argv._;
if (preview) {
let cmd = `npm run build`;
let cmd = `cross-env NODE_ENV=production vite build`;
await sh(cmd, {
async: true,
nopipe: true,
@@ -23,7 +23,7 @@ export const runBuild = async (preview = false) => {
if (!argvList.includes('no-conf')) {
await runBuildConfig();
}
await runUpdateHtml();
// await runUpdateHtml();
if (!preview) {
await startGzipStyle();
}

View File

@@ -1,103 +0,0 @@
import { readFileSync, writeFileSync, existsSync } from 'fs-extra';
import viteConfig, { htmlConfig } from '../../vite.config';
import { getCwdPath, successConsole, errorConsole } from '../utils';
import { GLOB_CONFIG_FILE_NAME } from '../constant';
import { hmScript } from './hm';
import HtmlMinifier from 'html-minifier';
const pkg = require('../../package.json');
const { title, addHm, cdnConf, useCdn, minify } = htmlConfig;
function injectTitle(html: string, htmlTitle: string) {
if (/<\/title>/.test(html)) {
return html.replace(/<\/title>/, `${htmlTitle}</title>`);
}
return html;
}
function injectConfigScript(html: string) {
const tag = `\t\t<script src='${viteConfig.base || './'}${GLOB_CONFIG_FILE_NAME}?v=${
pkg.version
}-${new Date().getTime()}'></script>`;
if (/<\/head>/.test(html)) {
return html.replace(/<\/head>/, `${tag}\n\t\t</head>`);
}
return html;
}
function injectHmScript(html: string) {
if (/<head>/.test(html)) {
return html.replace(/<head>/, `<head>\n${hmScript}`);
}
return html;
}
function injectCdnCss(html: string) {
if (!cdnConf) return html;
const { css } = cdnConf;
if (!css || css.length === 0) return html;
let cdnCssTag = '';
for (const cssLink of css) {
cdnCssTag += `<link rel="stylesheet" href="${cssLink}">`;
}
if (/<\/head>/.test(html)) {
return html.replace(/<\/head>/, `${cdnCssTag}\n\t\t</head>`);
}
return html;
}
function injectCdnjs(html: string) {
if (!cdnConf) return html;
const { js } = cdnConf;
if (!js || js.length === 0) return html;
let cdnJsTag = '';
for (const src of js) {
// TODO
// <script type="importmap">
// { "imports": {
// "vue": "https://cdnjs.cloudflare.com/ajax/libs/vue/3.0.0/vue.esm-browser.js",
// "vue-router": "https://cdnjs.cloudflare.com/ajax/libs/vue-router/4.0.0-alpha.13/vue-router.esm.js",
// "vuex": "https://cdnjs.cloudflare.com/ajax/libs/vuex/4.0.0-beta.2/vuex.esm-browser.js"
// } }
// </script>
cdnJsTag += `\t<script type="text/javascript" src="${src}"></script>\n`;
}
if (/<\/body>/.test(html)) {
return html.replace(/<\/body>/, `${cdnJsTag}\n</body>`);
}
return html;
}
export async function runUpdateHtml() {
const outDir = viteConfig.outDir || 'dist';
const indexPath = getCwdPath(outDir, 'index.html');
if (!existsSync(indexPath)) return;
try {
let processedHtml = '';
const rawHtml = readFileSync(indexPath, 'utf-8');
processedHtml = rawHtml;
processedHtml = injectTitle(processedHtml, title);
processedHtml = injectConfigScript(processedHtml);
if (addHm) {
processedHtml = injectHmScript(processedHtml);
}
if (useCdn) {
processedHtml = injectCdnCss(processedHtml);
processedHtml = injectCdnjs(processedHtml);
}
if (minify) {
const { enable, ...miniOpt } = minify;
if (enable) {
processedHtml = HtmlMinifier.minify(processedHtml, miniOpt);
}
}
writeFileSync(indexPath, processedHtml);
successConsole('Update Html Successfully!');
} catch (error) {
errorConsole('Update Html Error\n' + error);
}
}

View File

@@ -2,7 +2,6 @@
// https://github.com/luxueyan/vite-transform-globby-import/blob/master/src/index.ts
// TODO 目前还不能监听文件新增及删除 内容已经改变,缓存问题?
// 可以使用,先不打算集成
import { join } from 'path';
import { lstatSync } from 'fs';
import glob from 'glob';

View File

@@ -1,8 +1,8 @@
import { gzip } from 'zlib';
import { readFileSync, writeFileSync } from 'fs';
import { GzipPluginOptions } from './types';
import viteConfig from '../../../vite.config';
import { readAllFile, getCwdPath, isBuildGzip, isSiteMode } from '../../utils';
import viteConfig from '../../../../vite.config';
import { readAllFile, getCwdPath, isBuildGzip, isSiteMode } from '../../../utils';
export function startGzip(
fileContent: string | Buffer,

View File

@@ -0,0 +1,76 @@
import type { Plugin as VitePlugin } from 'vite';
import type { Plugin as rollupPlugin } from 'rollup';
import { createMockServer } from 'vite-plugin-mock';
import ViteHtmlPlugin from 'vite-plugin-html';
import PurgeIcons from 'vite-plugin-purge-icons';
import visualizer from 'rollup-plugin-visualizer';
import gzipPlugin from './gzip/index';
import { hmScript } from '../hm';
const pkg = require('../../../package.json');
import { isDevFn, isProdFn, isSiteMode, ViteEnv, isReportMode, isBuildGzip } from '../../utils';
import { GLOB_CONFIG_FILE_NAME } from '../../constant';
// gen vite plugins
export function createVitePlugins(viteEnv: ViteEnv) {
const { VITE_USE_MOCK, VITE_GLOB_APP_TITLE, VITE_PUBLIC_PATH } = viteEnv;
const vitePlugins: VitePlugin[] = [];
// vite-plugin-html
vitePlugins.push(
ViteHtmlPlugin({
// html title
title: VITE_GLOB_APP_TITLE,
minify: isProdFn(),
options: {
// Package and insert additional configuration files
injectConfig: isProdFn()
? `<script src='${VITE_PUBLIC_PATH || './'}${GLOB_CONFIG_FILE_NAME}?v=${
pkg.version
}-${new Date().getTime()}'></script>`
: '',
// Insert Baidu statistics code
hmScript: isSiteMode() ? hmScript : '',
},
})
);
// vite-plugin-purge-icons
vitePlugins.push(PurgeIcons());
// vite-plugin-mock
if (isDevFn() && VITE_USE_MOCK) {
// open mock
vitePlugins.push(
createMockServer({
ignore: /^\_/,
mockPath: 'mock',
})
);
}
return vitePlugins;
}
// gen rollup plugins
export function createRollupPlugin() {
const rollupPlugins: rollupPlugin[] = [];
if (isProdFn()) {
if (isReportMode()) {
// rollup-plugin-visualizer
rollupPlugins.push(
visualizer({ filename: './build/.cache/stats.html', open: true }) as Plugin
);
}
if (isBuildGzip() || isSiteMode()) {
// rollup-plugin-gizp
rollupPlugins.push(gzipPlugin());
}
}
return rollupPlugins;
}