4 * Watch changes to *.es6.js files and compile them to ES5 during development.
6 * @internal This file is part of the core javascript build process and is only
7 * meant to be used in that context.
12 const fs = require('fs');
13 const path = require('path');
14 const babel = require('babel-core');
15 const chokidar = require('chokidar');
17 // Logging human-readable timestamp.
18 const log = function log(message) {
19 // eslint-disable-next-line no-console
20 console.log(`[${new Date().toTimeString().slice(0, 8)}] ${message}`);
23 function addSourceMappingUrl(code, loc) {
24 return `${code}\n\n//# sourceMappingURL=${path.basename(loc)}`;
27 const fileMatch = './**/*.es6.js';
28 const watcher = chokidar.watch(fileMatch, {
30 ignored: 'node_modules/**'
33 const changedOrAdded = (filePath) => {
34 babel.transformFile(filePath, {
38 const fileName = filePath.slice(0, -7);
39 // we've requested for a sourcemap to be written to disk
40 const mapLoc = `${fileName}.js.map`;
42 fs.writeFileSync(mapLoc, JSON.stringify(result.map));
43 fs.writeFileSync(`${fileName}.js`, addSourceMappingUrl(result.code, mapLoc));
45 log(`'${filePath}' has been changed.`);
49 const unlinkHandler = (err) => {
56 .on('add', filePath => changedOrAdded(filePath))
57 .on('change', filePath => changedOrAdded(filePath))
58 .on('unlink', (filePath) => {
59 const fileName = filePath.slice(0, -7);
60 fs.stat(`${fileName}.js`, () => {
61 fs.unlink(`${fileName}.js`, unlinkHandler);
63 fs.stat(`${fileName}.js.map`, () => {
64 fs.unlink(`${fileName}.js.map`, unlinkHandler);
67 .on('ready', () => log(`Watching '${fileMatch}' for changes.`));