2024-07-18 14:15:56 +08:00
|
|
|
const fs = require('fs-extra')
|
|
|
|
const path = require('path')
|
|
|
|
|
|
|
|
function viteCopyToNewFolderPlugin(options = {}) {
|
|
|
|
const { outputDir } = options // 允许通过选项传递输出目录
|
|
|
|
return {
|
|
|
|
name: 'vite-plugin-copy-to-new-folder',
|
|
|
|
closeBundle() {
|
|
|
|
// 使用fs-extra的copy方法来复制目录
|
|
|
|
const distDir = path.resolve(process.cwd(), 'dist/build/h5')
|
|
|
|
const outDir = path.resolve(process.cwd(), 'dist/build', outputDir)
|
|
|
|
try {
|
|
|
|
fs.copySync(distDir, outDir, { overwrite: true })
|
|
|
|
} catch (e) {
|
|
|
|
console.log('复制打包文件出错-->', e)
|
|
|
|
}
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-07-19 18:21:53 +08:00
|
|
|
/**
|
|
|
|
* options下各个参数说明
|
|
|
|
* soure 路径
|
|
|
|
* target 目标文件夹
|
|
|
|
* mode 1代表删除target文件夹 2代表删除target以外的所有文件夹 默认1
|
|
|
|
*/
|
|
|
|
|
2024-07-18 14:15:56 +08:00
|
|
|
function vitePluginRemoveDir(options = {}) {
|
2024-07-19 18:21:53 +08:00
|
|
|
// 解构参数
|
|
|
|
const { source, target, mode = 1 } = options
|
2024-07-18 14:15:56 +08:00
|
|
|
return {
|
|
|
|
name: 'vite-plugin-remove-dir', // 插件名称
|
|
|
|
closeBundle() {
|
2024-07-19 18:21:53 +08:00
|
|
|
// if (mode === 2) {
|
|
|
|
// const all = fs.readdirSync(path.resolve(source))
|
|
|
|
// for (const item of all) {
|
|
|
|
// if (item !== target) {
|
|
|
|
// // 尝试删除目录
|
|
|
|
// const full = path.resolve(source, item)
|
|
|
|
// const isD = fs.statSync(full).isDirectory()
|
|
|
|
// console.log(item, isD)
|
|
|
|
// if (isD) {
|
|
|
|
// // try {
|
|
|
|
// // fs.removeSync(full)
|
|
|
|
// // console.log(`目录${fullPath}成功删除.`)
|
|
|
|
// // } catch (err) {
|
|
|
|
// // console.log(`目录${fullPath}删除失败-->${err}`)
|
|
|
|
// // }
|
|
|
|
// }
|
|
|
|
// }
|
|
|
|
// }
|
|
|
|
// return false
|
|
|
|
// }
|
2024-07-18 14:15:56 +08:00
|
|
|
setTimeout(() => {
|
2024-07-19 18:21:53 +08:00
|
|
|
const fullPath = path.resolve(source, target)
|
2024-07-18 14:15:56 +08:00
|
|
|
try {
|
|
|
|
fs.removeSync(fullPath)
|
|
|
|
console.log(`目录${fullPath}成功删除.`)
|
|
|
|
} catch (err) {
|
|
|
|
console.log(`目录${fullPath}删除失败-->${err}`)
|
|
|
|
}
|
|
|
|
}, 2000)
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
viteCopyToNewFolderPlugin,
|
|
|
|
vitePluginRemoveDir,
|
|
|
|
}
|