58 lines
1.7 KiB
TypeScript
58 lines
1.7 KiB
TypeScript
import type { PluginOption } from 'vite';
|
|
import * as fs from 'node:fs';
|
|
|
|
import path from 'node:path';
|
|
import * as process from 'node:process';
|
|
import normallize from 'normalize-path';
|
|
|
|
// export const defaultPagesRE = /src[/\\]pages(.*)[/\\](.*)[/\\](.*)\.vue$/;
|
|
export const defaultPagesRE = /src[/\\]pages([^/\\]*)[/\\]([^/\\]*)[/\\](.*)\.vue$/;
|
|
|
|
export interface Options {
|
|
pagesRE: RegExp
|
|
name: string
|
|
configPath: string
|
|
pluginName: string
|
|
DEBUG: boolean
|
|
}
|
|
|
|
export default function (options: Partial<Options> = {}) {
|
|
const {
|
|
pagesRE = defaultPagesRE,
|
|
name = './src/layout/AppProvider.vue',
|
|
pluginName = 'AppProvider',
|
|
// DEBUG = process.env.DEBUG,
|
|
} = options;
|
|
|
|
const template = fs.readFileSync(normalizePagePathFromBase(name), 'utf-8');
|
|
|
|
return <PluginOption>{
|
|
name: pluginName,
|
|
enforce: 'pre',
|
|
transform(code, id) {
|
|
id = normalizePagePathFromBase(id);
|
|
const regResult = pagesRE.exec(id);
|
|
if (regResult && (regResult[2] === regResult[3] || regResult[3] === 'index')) {
|
|
const oldTempleate = /<template>([\s\S]*)<\/template>/.exec(code);
|
|
const tmp_string = oldTempleate != null ? oldTempleate[1] : '';
|
|
const newTemplate = template.replace('<!-- template -->', tmp_string as string);
|
|
code = code.replace(/<template>([\s\S]*)<\/template>/, newTemplate);
|
|
}
|
|
return { code, map: null };
|
|
},
|
|
};
|
|
|
|
function normalizePagePathFromBase(file: string) {
|
|
return normallize(path.relative(process.cwd(), file));
|
|
}
|
|
|
|
// function debug(...args) {
|
|
// DEBUG &&
|
|
// console.log(
|
|
// c.dim(new Date().toLocaleTimeString()),
|
|
// c.bold(c.red(`[debug:${pluginName}]`)),
|
|
// ...args,
|
|
// )
|
|
// }
|
|
}
|