rollup-plugin-google-closure-compiler
Version:
Rollup plugin for invoking the Google Closure Compiler with Java.
51 lines (38 loc) • 1.45 kB
JavaScript
const tmp = require('tmp');
const fs = require('fs');
const ClosureCompiler = require('google-closure-compiler').compiler;
module.exports = function closure(flags = {}) {
return {
name: 'closure-compiler',
transformBundle(code) {
const jsFile = tmp.fileSync();
const mapFile = tmp.fileSync();
fs.writeFileSync(jsFile.name, code);
flags = Object.assign({
js: jsFile.name,
createSourceMap: mapFile.name,
processCommonJsModules: true,
}, flags);
const compiler = new ClosureCompiler(camelToUnderscore(flags));
const compile = new Promise(resolve => compiler.run((...args) => resolve(args)));
return compile.then(([exitCode, stdout, stderr]) => {
if (exitCode) {
throw new Error(`Closure compiler exited code ${exitCode}: ${stderr}`);
}
return { code: stdout, map: JSON.parse(fs.readFileSync(mapFile.name)), mapFile: mapFile.name };
});
}
};
}
const camelToUnderscore = camelOptions => {
const reg = /([A-Z])/g;
const ret = {};
Object.keys(camelOptions).forEach(key => {
const value = camelOptions[key];
if (reg.test(key)) {
key = key.replace(reg, char => '_' + char.toLowerCase())
}
ret[key] = value;
});
return ret;
}