60 lines
1.7 KiB
TypeScript
60 lines
1.7 KiB
TypeScript
import type { Plugin } from "vite";
|
|
import { glob } from "glob";
|
|
import * as path from "path";
|
|
import * as fs from "fs";
|
|
|
|
/**
|
|
|
|
*/
|
|
export type PluginOption = {
|
|
include: string[];
|
|
exclude?: string[];
|
|
preamble: string;
|
|
entry: string;
|
|
};
|
|
|
|
/**
|
|
* Per `option` have follow property:
|
|
* @param include
|
|
* value like ["src/**\/*.{tsx,jsx,ts,js}"]
|
|
* @param preamble
|
|
* value like `"export * from "`
|
|
*/
|
|
export function genIndex(...options: PluginOption[]): Plugin {
|
|
return {
|
|
name: "VITE_PLUGIN_GEN_INDEX",
|
|
|
|
config() {
|
|
options.forEach((opt) => {
|
|
const entryToFileArray: string[] = [];
|
|
const includeArray = opt.include;
|
|
const excludeArray = opt.exclude;
|
|
includeArray.forEach((ipath) => {
|
|
const files = glob.sync(ipath, { ignore: excludeArray });
|
|
|
|
files.forEach((file) => {
|
|
let entryToFile = path.relative(opt.entry, file);
|
|
// console.log(`origin: ${entryToFile}`);
|
|
|
|
// Fix the bug of path.relative, file in the same dir should start with [ ./ ] not [ ../ ]
|
|
if (entryToFile.startsWith("..")) {
|
|
entryToFile = entryToFile.substring(1);
|
|
// console.log(`after substring: ${entryToFile}`);
|
|
}
|
|
|
|
// Fix the bug of lib, default is output "\" , we need handle by self, replace "\" to "/" for Windows
|
|
entryToFile = entryToFile.replace(/\\/g, "/");
|
|
// console.log(`after replace: ${entryToFile} \n`);
|
|
|
|
entryToFileArray.push(
|
|
opt.preamble.concat(" ", "'", entryToFile, "';"),
|
|
);
|
|
});
|
|
});
|
|
|
|
fs.writeFileSync(opt.entry, entryToFileArray.join("\n"), "utf-8");
|
|
});
|
|
},
|
|
};
|
|
}
|