GoogleJavaScriptMinifier implements JavaScriptMinifier { @Override public String compress(String resourceName, String content) { try { Compiler compiler = new Compiler(new LogErrorManager(resourceName)); compiler.disableThreads(); SourceFile sourceFile = SourceFile.fromCode(resourceName, content); CompilerOptions compilerOptions = new CompilerOptions(); CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel( compilerOptions); compilerOptions.setEmitUseStrict(false); compilerOptions.setLanguageIn( CompilerOptions.LanguageMode.ECMASCRIPT_NEXT); compilerOptions.setResolveSourceMapAnnotations(false); compiler.compile( SourceFile.fromCode("extern", StringPool.BLANK), sourceFile, compilerOptions); if (compiler.hasErrors()) { return content; } return compiler.toSource(); } finally { if (_clearThreadTraceMethod != null) { try { _clearThreadTraceMethod.invoke(null); } catch (ReflectiveOperationException reflectiveOperationException) { if (_log.isWarnEnabled()) { _log.warn( "Unable to clear thread local for ThreadTrace", reflectiveOperationException); } } } } }  @Override String compress(String resourceName, String content);  }
@Test public void testMinifierCode() { GoogleJavaScriptMinifier googleJavaScriptMinifier = new GoogleJavaScriptMinifier(); String code = "function(){ var invalidFunctionExpression; }"; try (CaptureHandler captureHandler = JDKLoggerTestUtil.configureJDKLogger( GoogleJavaScriptMinifier.class.getName(), Level.SEVERE)) { String minifiedJS = googleJavaScriptMinifier.compress("test", code); Assert.assertEquals(44, minifiedJS.length()); List<LogRecord> logRecords = captureHandler.getLogRecords(); Assert.assertEquals(logRecords.toString(), 2, logRecords.size()); LogRecord logRecord = logRecords.get(0); Assert.assertEquals( "(test:1): Parse error. 'identifier' expected " + "[JSC_PARSE_ERROR]", logRecord.getMessage()); logRecord = logRecords.get(1); Assert.assertEquals( "(test): 1 error(s), 0 warning(s)", logRecord.getMessage()); captureHandler.resetLogLevel(Level.SEVERE); } }
@Test public void testMinifierSpaces() { GoogleJavaScriptMinifier googleJavaScriptMinifier = new GoogleJavaScriptMinifier(); String code = " \t\r\n"; String minifiedJS = googleJavaScriptMinifier.compress("test", code); Assert.assertEquals(0, minifiedJS.length()); }