import {
Plugin,
ResolvedConfig,
} from 'vite'
export interface Options {
inject?: string
local?: string,
mode?: string
}
export function expandPlugin(options: Options | Options[] = {}): any {
let config: ResolvedConfig;
let opts = Array.isArray(options) ? options : [options]
return {
name: 'expand-plugin',
configResolved(_config: any) {
config = _config;
},
transformIndexHtml(html: string) {
let env = config.env.MODE || 'development';
for (let k in opts) {
if (opts[k].inject) {
if (!opts[k].mode || opts[k].mode == env)
html = replaceHtml(html, opts[k].inject, opts[k].local);
}
}
return html
},
apply: 'build',
}
}
function replaceHtml(html: string, inject: any, local: string = '') {
if (local === 'head-after') {
html = html.replace(`</head>`, `${inject}</head>`)
} else if (local === 'body-after') {
html = html.replace(`</body>`, `${inject}</body>`)
} else if (local === '<!--seo-cdn-->') {
html = html.replace(`<!--seo-cdn-->`, `${inject}`)
} else html = html.replace(`</body>`, `${inject}</body>`)
return html
}