babel-es6-watch.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * @file
  3. *
  4. * Watch changes to *.es6.js files and compile them to ES5 during development.
  5. *
  6. * @internal This file is part of the core javascript build process and is only
  7. * meant to be used in that context.
  8. */
  9. 'use strict';
  10. const fs = require('fs');
  11. const path = require('path');
  12. const babel = require('babel-core');
  13. const chokidar = require('chokidar');
  14. // Logging human-readable timestamp.
  15. const log = function log(message) {
  16. // eslint-disable-next-line no-console
  17. console.log(`[${new Date().toTimeString().slice(0, 8)}] ${message}`);
  18. };
  19. function addSourceMappingUrl(code, loc) {
  20. return `${code}\n\n//# sourceMappingURL=${path.basename(loc)}`;
  21. }
  22. const fileMatch = './**/*.es6.js';
  23. const watcher = chokidar.watch(fileMatch, {
  24. ignoreInitial: true,
  25. ignored: 'node_modules/**'
  26. });
  27. const changedOrAdded = (filePath) => {
  28. babel.transformFile(filePath, {
  29. sourceMaps: true,
  30. comments: false
  31. }, (err, result) => {
  32. const fileName = filePath.slice(0, -7);
  33. // we've requested for a sourcemap to be written to disk
  34. const mapLoc = `${fileName}.js.map`;
  35. fs.writeFileSync(mapLoc, JSON.stringify(result.map));
  36. fs.writeFileSync(`${fileName}.js`, addSourceMappingUrl(result.code, mapLoc));
  37. log(`'${filePath}' has been changed.`);
  38. });
  39. };
  40. const unlinkHandler = (err) => {
  41. if (err) {
  42. log(err);
  43. }
  44. };
  45. watcher
  46. .on('add', filePath => changedOrAdded(filePath))
  47. .on('change', filePath => changedOrAdded(filePath))
  48. .on('unlink', (filePath) => {
  49. const fileName = filePath.slice(0, -7);
  50. fs.stat(`${fileName}.js`, () => {
  51. fs.unlink(`${fileName}.js`, unlinkHandler);
  52. });
  53. fs.stat(`${fileName}.js.map`, () => {
  54. fs.unlink(`${fileName}.js.map`, unlinkHandler);
  55. });
  56. })
  57. .on('ready', () => log(`Watching '${fileMatch}' for changes.`));