Search code examples
javascriptnode.jsnpmgoogle-closure-compileruglifyjs

google-closure-compiler basic process example


could anyone please add a snippet to a google-closure-compiler basic process, I am trying unsuccessfully to this via js code. I am using the exmple snippet from the official npm page. when I run it, something seem to happen but the output file isn't created.

My code:

const ClosureCompiler = require('google-closure-compiler').jsCompiler;

console.log(ClosureCompiler.CONTRIB_PATH); // absolute path to the contrib folder which contains externs

const closureCompiler = new ClosureCompiler({
  compilation_level: 'ADVANCED'
});

const compilerProcess = closureCompiler.run([{
 path: './',
 src: 'a.js',
 sourceMap: null // optional input source map
}], (exitCode, stdOut, stdErr) => {
    console.log(stdOut)
  //compilation complete
});


Solution

  • Building from what you had, I've changed just a few things:

    1) The src attribute is not a path it is the file: read the file in this case with fs.readFileSync.

    2) The output is returned in the callback: you'll need to write it to the disk.

    Files:

    index.js

    const ClosureCompiler = require('google-closure-compiler').jsCompiler;
    const {writeFile, readFileSync} = require('fs');
    
    const closureCompiler = new ClosureCompiler({
      compilation_level: 'ADVANCED'
    });
    let src = readFileSync('a.js', 'UTF-8');
    const compilerProcess = closureCompiler.run([{
     path: './',
     src: src,
     sourceMap: null
    }], (exitCode, stdOut, stdErr) => {
      stdOut.map((fileResults) => {
        writeFile(fileResults.path, fileResults.src, () => {});
      });
    });
    

    a.js

    console.log('hello world!')
    

    compiled.js

    console.log("hello world!");