watchAndCopy.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import { watch } from 'chokidar'
  2. import { copy, remove } from 'fs-extra'
  3. import { normalizePath } from 'vite'
  4. function toClientAndNode(method, file) {
  5. file = normalizePath(file)
  6. if (method === 'copy') {
  7. copy(file, file.replace(/^src\/shared\//, 'src/node/'))
  8. copy(file, file.replace(/^src\/shared\//, 'src/client/'))
  9. } else if (method === 'remove') {
  10. remove(file.replace(/^src\/shared\//, 'src/node/'))
  11. remove(file.replace(/^src\/shared\//, 'src/client/'))
  12. }
  13. }
  14. function toDist(file) {
  15. return normalizePath(file).replace(/^src\//, 'dist/')
  16. }
  17. // copy shared files to the client and node directory whenever they change.
  18. watch('src/shared', {
  19. ignored: (path, stats) => stats?.isFile() && !path.endsWith('.ts')
  20. })
  21. .on('change', (file) => toClientAndNode('copy', file))
  22. .on('add', (file) => toClientAndNode('copy', file))
  23. .on('unlink', (file) => toClientAndNode('remove', file))
  24. // copy non ts files, such as an html or css, to the dist directory whenever
  25. // they change.
  26. watch('src/client', {
  27. ignored: (path, stats) =>
  28. stats?.isFile() && (path.endsWith('.ts') || path.endsWith('tsconfig.json'))
  29. })
  30. .on('change', (file) => copy(file, toDist(file)))
  31. .on('add', (file) => copy(file, toDist(file)))
  32. .on('unlink', (file) => remove(toDist(file)))