|
|
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);
|
|
|
|
|
|
// 添加文件更改监听
|
|
|
server.watcher.on('change', (filePath) => {
|
|
|
moveMarkdownFiles(SRC_DIR);
|
|
|
});
|
|
|
},
|
|
|
// 打包时执行(开发模式下也会执行,所以不需要configureServer)
|
|
|
buildStart: () => {
|
|
|
moveMarkdownFiles(SRC_DIR);
|
|
|
},
|
|
|
};
|
|
|
}
|