d614774f2914a8378662d457b8c92232d1725ad7
[yaffs-website] / web / core / scripts / js / babel-es6-watch.js
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
10 'use strict';
11
12 const fs = require('fs');
13 const path = require('path');
14 const babel = require('babel-core');
15 const chokidar = require('chokidar');
16
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}`);
21 };
22
23 function addSourceMappingUrl(code, loc) {
24   return `${code}\n\n//# sourceMappingURL=${path.basename(loc)}`;
25 }
26
27 const fileMatch = './**/*.es6.js';
28 const watcher = chokidar.watch(fileMatch, {
29   ignoreInitial: true,
30   ignored: 'node_modules/**'
31 });
32
33 const changedOrAdded = (filePath) => {
34   babel.transformFile(filePath, {
35     sourceMaps: true,
36     comments: false
37   }, (err, result) => {
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`;
41
42     fs.writeFileSync(mapLoc, JSON.stringify(result.map));
43     fs.writeFileSync(`${fileName}.js`, addSourceMappingUrl(result.code, mapLoc));
44
45     log(`'${filePath}' has been changed.`);
46   });
47 };
48
49 const unlinkHandler = (err) => {
50   if (err) {
51     log(err);
52   }
53 };
54
55 watcher
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);
62     });
63     fs.stat(`${fileName}.js.map`, () => {
64       fs.unlink(`${fileName}.js.map`, unlinkHandler);
65     });
66   })
67   .on('ready', () => log(`Watching '${fileMatch}' for changes.`));