사용자 도구

사이트 도구


javascript:performance:closurecompiler

차이

문서의 선택한 두 판 사이의 차이를 보여줍니다.

차이 보기로 링크

양쪽 이전 판 이전 판
다음 판
이전 판
javascript:performance:closurecompiler [2014/08/25 11:05]
kwon37xi [Closure Compiler API]
javascript:performance:closurecompiler [2015/06/18 11:19] (현재)
kwon37xi [설치 사용]
줄 27: 줄 27:
   * [[https://developers.google.com/closure/compiler/docs/compilation_levels|컴파일 레벨]]   * [[https://developers.google.com/closure/compiler/docs/compilation_levels|컴파일 레벨]]
     * ''WHITESPACE_ONLY'' : 공백과 주석 제거등만 실행     * ''WHITESPACE_ONLY'' : 공백과 주석 제거등만 실행
-    * ''SIMPLE_OPTIMIZATIONS'' : 기본값. 공백제거, 세미콜론 보정등.+    * ''SIMPLE_OPTIMIZATIONS'' : 기본값. 공백제거, 세미콜론 보정등. 가끔 오보정이 일아났다.
     * ''ADVANCED_OPTIMIZATIONS'' : 더 강력한 압축. 불필요한 코드 삭제 등.     * ''ADVANCED_OPTIMIZATIONS'' : 더 강력한 압축. 불필요한 코드 삭제 등.
     * 적용<code sh>     * 적용<code sh>
줄 33: 줄 33:
 </code> </code>
   * Options   * Options
-    * ''--js VAL'' : 컴파일 대상 파일 +    * ''%%--%%js VAL'' : 컴파일 대상 파일 
-    * ''--js_output_file VAL'' : 컴파일 결과 파일. 저장하지 않으면 표준출력. +    * ''%%--%%js_output_file VAL'' : 컴파일 결과 파일. 저장하지 않으면 표준출력. 
-    * ''--charset VAL'' : 입출력 캐릭터셋 +    * ''%%--%%charset VAL'' : 입출력 캐릭터셋 
-    * ''--compilation-level [WHITESPACE_ONLY | SIMPLE_OPTIMIZATIONS | ADVANCED_OPTIMZATIONS]'' : 컴파일 레벨 지정+    * ''%%--%%compilation-level [WHITESPACE_ONLY | SIMPLE_OPTIMIZATIONS | ADVANCED_OPTIMZATIONS]'' : 컴파일 레벨 지정
  
 ===== Ant 연동 ===== ===== Ant 연동 =====
줄 78: 줄 78:
   * [[https://github.com/eriwen/gradle-js-plugin/blob/master/src/main/groovy/com/eriwen/gradle/js/JsMinifier.groovy|JsMinifier.groovy]]에서 [[https://developers.google.com/closure/compiler/|ClosureCompiler]]의 API 사용법 예제를 볼 수 있다.   * [[https://github.com/eriwen/gradle-js-plugin/blob/master/src/main/groovy/com/eriwen/gradle/js/JsMinifier.groovy|JsMinifier.groovy]]에서 [[https://developers.google.com/closure/compiler/|ClosureCompiler]]의 API 사용법 예제를 볼 수 있다.
   * 혹은 ''com.google.javascript.jscomp.CommandLineRunner'' 참조   * 혹은 ''com.google.javascript.jscomp.CommandLineRunner'' 참조
-<code groovy+  * 일괄 Minify 예<code java> 
-    void minifyJsFile(final Set<File> inputFiles, final Set<File> externsFiles, final File outputFile, final CompilerOptions options, +import java.io.*; 
-            final String warningLevel, final String compilationLevel) { +import java.nio.charset.Charset; 
-        Compiler compiler = new Compiler() +import java.nio.file.*; 
-        CompilationLevel.valueOf(compilationLevel).setOptionsForCompilationLevel(options+import java.nio.file.attribute.BasicFileAttributes; 
-        options.outputCharset 'utf-8' // 인코딩을 지정해야 올바르게 한글이 출력된다. +import java.util.ArrayList; 
-        WarningLevel level = WarningLevel.valueOf(warningLevel) +import java.util.List; 
-        level.setOptionsForWarningLevel(options+ 
-        List<JSSourceFile> externs CommandLineRunner.getDefaultExterns() +import com.google.javascript.jscomp.*; 
-        if (externsFiles.size()) { +import com.google.javascript.jscomp.Compiler; 
-            externs.addAll(externsFiles.collect() { JSSourceFile.fromFile(it) })+ 
 +public class BatchJsMinify { 
 +    private static final String[] EXCLUDE_PATTERNS = { ".min.js""-min.js" }; 
 +    private static final CompilationLevel DEFAULT_COMPILATION_LEVEL = CompilationLevel.SIMPLE_OPTIMIZATIONS; 
 + 
 +    private String srcDirName; 
 +    private final File srcDir; 
 + 
 +    private String destDirName; 
 +    private final File destDir; 
 + 
 +    private com.google.javascript.jscomp.Compiler compiler = new Compiler();; 
 +    private CompilerOptions options = new CompilerOptions()
 +    private WarningLevel warningLevel = WarningLevel.QUIET; 
 + 
 +    public BatchJsMinify(String srcDirName, String destDirName{ 
 +        this.srcDirName srcDirName; 
 +        this.destDirName = destDirName; 
 +        srcDir = new File(srcDirName); 
 +        destDir new File(destDirName)
 + 
 +        if (!srcDir.exists() || !srcDir.isDirectory()) { 
 +            throw new IllegalArgumentException(srcDirName + " must exist and be a directory.");
         }         }
-        List<JSSourceFileinputs new ArrayList<JSSourceFile>() + 
-        inputFiles.each inputFile -> +        destDir.mkdirs(); 
-          inputs.add(JSSourceFile.fromFile(inputFile))+    } 
 + 
 +    public void compile() throws IOException { 
 +        options.setCodingConvention(CodingConventions.getDefault()); 
 +        options.setOutputCharset("UTF-8"); 
 + 
 +        warningLevel.setOptionsForWarningLevel(options); 
 +        DEFAULT_COMPILATION_LEVEL.setOptionsForCompilationLevel(options); 
 + 
 +        final List<SourceFilejsSourceFiles getSourceFiles()
 + 
 +        if (jsSourceFiles == null || jsSourceFiles.size() == 0) 
 +            System.out.println("Nothing to compile.")
 +            return;
         }         }
-        Result result = compiler.compile(externsinputs, options)+ 
 +        final List<SourceFile> defaultExterns = CommandLineRunner.getDefaultExterns(); 
 + 
 +        compiler.disableThreads(); // thread가 활성화 돼 있으면 오히려 종료가 늦게 되었다. 
 +        final Result result = compiler.compile(defaultExternsjsSourceFiles, options)
         if (result.success) {         if (result.success) {
-            outputFile.write(compiler.toSource())+            writeToFile(jsSourceFiles);
         } else {         } else {
-            result.errors.each { +            printErrors(result);
-                println "${it.sourceName}:${it.lineNumber} - ${it.description}" +
-            }+
         }         }
 +
     }     }
-</code> 
  
 +    private void printErrors(Result result) {
 +        for (JSError error : result.errors) {
 +            System.err.println("Error : " + error.sourceName + ":" + error.lineNumber + " - " + error.description);
 +        }
 +    }
  
 +    private List<SourceFile> getSourceFiles() throws IOException {
 +        final List<SourceFile> jsSourceFiles = new ArrayList<>();
 +        Files.walkFileTree(Paths.get(srcDirName), new SimpleFileVisitor<Path>() {
 +                @Override
 +                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
 +                throws IOException {
 +                String filename = file.toString();
 +
 +                if (filename.endsWith(".js") && !filename.endsWith(".min.js") && !filename.endsWith("-min.js")) {
 +                final SourceFile sourceFile = SourceFile.fromFile(file.toFile(), Charset.forName("UTF-8"));
 +                jsSourceFiles.add(sourceFile);
 +                }
 +                return FileVisitResult.CONTINUE;
 +                }
 +                });
 +        return jsSourceFiles;
 +    }
 +
 +    private void writeToFile(List<SourceFile> jsSourceFiles) {
 +        final String[] minified = compiler.toSourceArray();
 +
 +        for (int i = 0; i < jsSourceFiles.size(); i++) {
 +            final SourceFile sourceFile = jsSourceFiles.get(i);
 +            String fileRestPath = sourceFile.getOriginalPath().replace(srcDirName, "");
 +            final File destFile = new File(destDir, fileRestPath);
 +            destFile.getParentFile().mkdirs();
 +
 +            System.out.println("Writing minified js file : " + destFile.getAbsolutePath());
 +
 +            try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destFile), "UTF-8"))) {
 +                writer.write(minified[i]);
 +            } catch (IOException e) {
 +                throw new IllegalStateException("minified js file save error.", e);
 +            }
 +        }
 +    }
 +}
 +</code>
javascript/performance/closurecompiler.1408932336.txt.gz · 마지막으로 수정됨: 2014/08/25 11:05 저자 kwon37xi