watch.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { exec } from 'child_process'
  2. import { watch } from 'chokidar'
  3. import { copyFile as _copyFile, existsSync, mkdirSync, unlink } from 'fs'
  4. import { basename, join } from 'path'
  5. const srcDir = 'src/plugins'
  6. const distDir = 'dist/plugins'
  7. if (!existsSync(distDir)) {
  8. mkdirSync(distDir, { recursive: true })
  9. }
  10. function copyFile(filePath) {
  11. const srcPath = filePath
  12. const distPath = join(distDir, basename(filePath))
  13. _copyFile(srcPath, distPath, (err) => {
  14. if (err) throw err
  15. console.log(`${srcPath} was copied to ${distPath}`)
  16. })
  17. }
  18. exec('npx pkgroll --watch', (err, stdout, stderr) => {
  19. if (err) {
  20. console.error(err)
  21. return
  22. }
  23. console.log(stdout)
  24. })
  25. // 监听文件变化
  26. const watcher = watch(srcDir, { ignored: /(^|[/\\])\../ })
  27. watcher.on('add', (filePath) => {
  28. if (filePath.endsWith('.yml')) {
  29. copyFile(filePath)
  30. }
  31. })
  32. watcher.on('change', (filePath) => {
  33. if (filePath.endsWith('.yml')) {
  34. copyFile(filePath)
  35. }
  36. })
  37. watcher.on('unlink', (filePath) => {
  38. if (filePath.endsWith('.yml')) {
  39. const distPath = join(distDir, basename(filePath))
  40. unlink(distPath, (err) => {
  41. if (err) throw err
  42. console.log(`${distPath} was removed`)
  43. })
  44. }
  45. })
  46. console.log(`Watching ${srcDir} directory...`)