babel-worker.js (1494B)
1 /* global onmessage: true, postMessage: false */ 2 'use strict'; 3 4 const fs = require('fs-extra'); 5 const path = require('path'); 6 const babel = require('babel-core'); 7 const multimatch = require('multimatch'); 8 const options = JSON.parse(fs.readFileSync('.babelrc')); 9 const cluster = require('cluster'); 10 11 /* exported onmessage */ 12 async function babelWorker(ev) { 13 const t1 = Date.now(); 14 const sourcefile = ev.file; 15 const outfile = path.join('build', sourcefile); 16 const postError = (error) => { 17 process.send({ 18 sourcefile, 19 outfile, 20 error 21 }); 22 }; 23 24 var isSkipped = false; 25 var transformed; 26 27 try { 28 let contents = await fs.readFile(sourcefile, 'utf8'); 29 if (sourcefile === 'resource/react-dom.js') { 30 // patch react 31 transformed = contents.replace(/ownerDocument\.createElement\((.*?)\)/gi, 'ownerDocument.createElementNS(DOMNamespaces.html, $1)'); 32 } else if ('ignore' in options && options.ignore.some(ignoreGlob => multimatch(sourcefile, ignoreGlob).length)) { 33 transformed = contents; 34 isSkipped = true; 35 } else { 36 try { 37 transformed = babel.transform(contents, options).code; 38 } catch (error) { return postError(`Babel error: ${error}`);} 39 } 40 41 await fs.outputFile(outfile, transformed); 42 const t2 = Date.now(); 43 process.send({ 44 isSkipped, 45 sourcefile, 46 outfile, 47 processingTime: t2 - t1 48 }); 49 } catch (error) { return postError(`I/O error: ${error}`); } 50 } 51 52 module.exports = babelWorker; 53 54 if (cluster.isWorker) { 55 process.on('message', babelWorker); 56 }