You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
2.4 KiB
TypeScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import fs from 'fs';
import path from 'path';
const SRC_DIR = path.resolve(process.cwd(), 'src');
const PUBLIC_MD_DIR = path.resolve(process.cwd(), 'public/md');
const moveMarkdownFiles = (dir: string) => {
// 获取指定目录下的文件
const files = fs.readdirSync(dir);
// 遍历文件
files.forEach((file) => {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
// 如果是目录,递归调用
moveMarkdownFiles(filePath);
} else if (file.endsWith('.md')) {
// 如果是文件,且是.md文件复制到public/md目录下
const distPath = path.join(PUBLIC_MD_DIR, path.basename(filePath));
// 检查目标文件是否存在
if (!fs.existsSync(distPath)) {
fs.copyFileSync(filePath, distPath);
console.log(`自定义vite插件复制 ${filePath}${distPath}(新增)`);
} else {
// 比较文件大小
// const sourceFileSize = stat.size;
// const distFileSize = fs.statSync(distPath).size;
// if (sourceFileSize !== distFileSize) {
// fs.copyFileSync(filePath, distPath);
// console.log(`自定义vite插件复制 ${filePath} 到 ${distPath}(文件大小不一致)`);
// }
// 读取源文件和目标文件的内容
const sourceFileContent = fs.readFileSync(filePath, 'utf-8');
const distFileContent = fs.readFileSync(distPath, 'utf-8');
if (sourceFileContent !== distFileContent) {
fs.copyFileSync(filePath, distPath);
console.log(`自定义vite插件复制 ${filePath}${distPath}(文件内容不一致)`);
}
}
}
});
};
export default function () {
// 确保public/md目标目录存在
if (!fs.existsSync(PUBLIC_MD_DIR)) {
fs.mkdirSync(PUBLIC_MD_DIR, { recursive: true });
}
return {
name: 'move-md-plugin',
// 开发服务器启动时执行
// configureServer: (server) => {
// moveMarkdownFiles(SRC_DIR);
// },
// 打包时执行(开发模式下也会执行所以不需要configureServer)
buildStart: () => {
moveMarkdownFiles(SRC_DIR);
},
};
}