import fs from "node:fs"; import path from "node:path"; import type { ResolvedConfig } from "vite"; export interface ViteConfitExtendOptions { indexPath: string; } export default function viteConfitExtend(options?: ViteConfitExtendOptions) { let _config: ResolvedConfig; const _options = options; return { name: "file-manager", writeBundle: () => { if (_config.command == "build") { //入口文件注入常量<%=xxx%> const defines = _config.define; if (defines) { const indexFile = path.resolve( _config.root, _config.build.outDir, "index.html" ); let htmlStr = fs.readFileSync(indexFile, "utf-8"); const reg = new RegExp("<%=([\\s]*)([\\S]+?)([\\s]*)%>", "g"); for (const item of htmlStr.matchAll(reg)) { const key = item[2]; if (key && key in defines) { const val = defines[key]; const rep = new RegExp(item[0], "g"); htmlStr = htmlStr.replace(rep, val); } } fs.writeFileSync(indexFile, htmlStr); } } }, configResolved(config: ResolvedConfig) { _config = config; }, closeBundle() { if (_config.command == "build" && _options) { if (_options.indexPath) { fs.renameSync( path.resolve(_config.root, _config.build.outDir, "index.html"), path.resolve(_config.root, _config.build.outDir, _options.indexPath) ); console.warn(`indexPath: ${_options.indexPath}`); } } }, }; }