| 1 | 'use strict'; |
| 2 | |
| 3 | const ClosureCompiler = require('google-closure-compiler').compiler; |
| 4 | const {promisify} = require('util'); |
| 5 | const fs = require('fs'); |
| 6 | const tmp = require('tmp'); |
| 7 | const writeFileAsync = promisify(fs.writeFile); |
| 8 | |
| 9 | function compile(flags) { |
| 10 | return new Promise((resolve, reject) => { |
| 11 | const closureCompiler = new ClosureCompiler(flags); |
| 12 | closureCompiler.run(function (exitCode, stdOut, stdErr) { |
| 13 | if (!stdErr) { |
| 14 | resolve(stdOut); |
| 15 | } else { |
| 16 | reject(new Error(stdErr)); |
| 17 | } |
| 18 | }); |
| 19 | }); |
| 20 | } |
| 21 | |
| 22 | module.exports = function closure(flags = {}) { |
| 23 | return { |
| 24 | name: 'scripts/rollup/plugins/closure-plugin', |
| 25 | async renderChunk(code, chunk, options) { |
| 26 | const inputFile = tmp.fileSync(); |
| 27 | |
| 28 | // Tell Closure what JS source file to read, and optionally what sourcemap file to write |
| 29 | const finalFlags = { |
| 30 | ...flags, |
| 31 | js: inputFile.name, |
| 32 | }; |
| 33 | |
| 34 | await writeFileAsync(inputFile.name, code, 'utf8'); |
| 35 | const compiledCode = await compile(finalFlags); |
| 36 | |
| 37 | inputFile.removeCallback(); |
| 38 | return {code: compiledCode}; |
| 39 | }, |
| 40 | }; |
| 41 | }; |