watcher.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. const fs = require('node:fs');
  2. const chokidar = require('chokidar');
  3. const path = require('node:path');
  4. const jscompiler = require('./jscompiler');
  5. const postcssCompiler = require('./postcss');
  6. const terser = require('terser');
  7. let config = {
  8. js: {
  9. src: 'src/js',
  10. dest: 'dist/js',
  11. },
  12. css: {
  13. src: 'src/postcss',
  14. dest: 'dist/css',
  15. }
  16. };
  17. /**
  18. * Handle Javascript files
  19. * compile the javascript files
  20. * to es2015, minify and sync the files
  21. *
  22. * @param {string} file path
  23. */
  24. async function handleJavascript(file) {
  25. file = path.join(config.js.src, 'glightbox.js');
  26. const name = path.basename(file);
  27. const res = await jscompiler({
  28. file,
  29. dest: config.js.dest,
  30. format: 'umd',
  31. sourcemap: false,
  32. moduleID: 'GLightbox'
  33. }).catch(error => console.log(error));
  34. if (!res) {
  35. console.log('Build Error', `View logs for more info`);
  36. console.log(res)
  37. return false;
  38. }
  39. const minName = name.replace('.js', '.min.js');
  40. const processed = path.join(config.js.dest, name);
  41. const code = fs.readFileSync(processed, 'utf8');
  42. const minified = terser.minify(code);
  43. const minifyPath = path.join(config.js.dest, minName);
  44. fs.writeFileSync(minifyPath, minified.code);
  45. console.log('Javascript Build', `Compiled and Minified ${name}`);
  46. }
  47. /**
  48. * Handle Postcss files
  49. * compile the css files
  50. *
  51. * @param {string} file path
  52. */
  53. async function handlePostCSS(file) {
  54. const name = path.basename(file);
  55. const dest = config.css.dest;
  56. let res = await postcssCompiler({
  57. file,
  58. dest,
  59. minify: true
  60. }).catch(error => console.log(error));
  61. if (!res) {
  62. return false;
  63. }
  64. console.log('PostCSS Build', `Compiled and Minified ${name}`);
  65. }
  66. /**
  67. * Watcher
  68. * what the files for the backedn
  69. * this includes js and css files
  70. */
  71. function filesWatcher() {
  72. const watcher = chokidar.watch(['src'], {
  73. ignored: ['.DS_Store', 'src/js/.jshintrc', 'src/js/.babelrc'],
  74. persistent: true,
  75. depth: 3,
  76. awaitWriteFinish: {
  77. stabilityThreshold: 500,
  78. pollInterval: 500
  79. },
  80. });
  81. watcher.on('change', path => {
  82. if (path.endsWith('.js')) {
  83. return handleJavascript(path);
  84. }
  85. if (path.endsWith('.css')) {
  86. return handlePostCSS(path);
  87. }
  88. })
  89. watcher.on('ready', () => console.log('Watching files', 'Initial scan complete. Ready for changes'))
  90. }
  91. filesWatcher();