com.google.javascript.jscomp.Compiler类的使用及代码示例

x33g5p2x  于2022-01-18 转载在 JavaScript  
字(11.7k)|赞(0)|评价(0)|浏览(409)

本文整理了Java中com.google.javascript.jscomp.Compiler类的一些代码示例,展示了Compiler类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Compiler类的具体详情如下:
包路径:com.google.javascript.jscomp.Compiler
类名称:Compiler

Compiler介绍

[英]Compiler (and the other classes in this package) does the following:

  • parses JS code
  • checks for undefined variables
  • performs optimizations such as constant folding and constants inlining
  • renames variables (to short names)
  • outputs compact JavaScript code
    External variables are declared in 'externs' files. For instance, the file may include definitions for global javascript/browser objects such as window, document.
    [中]编译器(以及此包中的其他类)执行以下操作:
    *解析JS代码
    *检查未定义的变量
    *执行优化,例如常量折叠和常量内联
    *重命名变量(短名称)
    *输出紧凑的JavaScript代码
    外部变量在“externs”文件中声明。例如,该文件可能包括全局javascript/浏览器对象(如窗口、文档)的定义。

代码示例

代码示例来源:origin: jooby-project/jooby

@Override
public String process(final String filename, final String source, final Config conf,
  final ClassLoader loader) throws Exception {
 final CompilerOptions copts = new CompilerOptions();
 copts.setCodingConvention(new ClosureCodingConvention());
 copts.setOutputCharset(StandardCharsets.UTF_8);
 copts.setWarningLevel(DiagnosticGroups.CHECK_VARIABLES, CheckLevel.WARNING);
 CompilationLevel level = level(get("level"));
 level.setOptionsForCompilationLevel(copts);
 Compiler.setLoggingLevel(Level.SEVERE);
 Compiler compiler = new Compiler();
 compiler.disableThreads();
 compiler.initOptions(copts);
 List<SourceFile> externs = externs(copts);
 Result result = compiler.compile(externs,
   ImmutableList.of(SourceFile.fromCode(filename, source)), copts);
 if (result.success) {
  return compiler.toSource();
 }
 List<AssetProblem> errors = Arrays.stream(result.errors)
   .map(error -> new AssetProblem(error.sourceName, error.lineNumber, error.getCharno(),
     error.description, null))
   .collect(Collectors.toList());
 throw new AssetException(name(), errors);
}

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

protected String compileJs(SourceFile input, String filename) throws ResourceMinificationException, IOException {
  Compiler compiler = getCompiler();
  List<SourceFile> builtinExterns = AbstractCommandLineRunner.getBuiltinExterns(CompilerOptions.Environment.CUSTOM);
  Result result = compiler.compile(builtinExterns, Arrays.asList(input), getCompilerOptions());
  String compiled = compiler.toSource();
  if (!result.success || StringUtils.isBlank(compiled)) {
    StringBuilder errorString = new StringBuilder("\n");
    if (result.errors != null) {
      for (int i = 0; i < result.errors.length; i++) {
        errorString.append(result.errors[i].description + "\n");
      }
    }
    throw new ResourceMinificationException("Error minifying js file " + filename + errorString);
  }
  return compiler.toSource();
}

代码示例来源:origin: com.atlassian.maven.plugins/maven-amps-plugin

public static String compile(String code) {
  Compiler compiler = new Compiler();
  CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options);
  JSSourceFile extern = JSSourceFile.fromCode("externs.js","function alert(x) {}");
  // The dummy input name "input.js" is used here so that any warnings or
  // errors will cite line numbers in terms of input.js.
  JSSourceFile input = JSSourceFile.fromCode("input.js", code);
  // compile() returns a Result, but it is not needed here.
  compiler.compile(extern, input, options);
  // The compiler is responsible for generating the compiled code; it is not
  // accessible via the Result.
  return compiler.toSource();
}

代码示例来源:origin: alexo/wro4j

private Compiler newCompiler(final CompilerOptions compilerOptions) {
 Compiler.setLoggingLevel(Level.SEVERE);
 final Compiler compiler = new Compiler();
 compilationLevel.setOptionsForCompilationLevel(compilerOptions);
 // make it play nice with GAE
 compiler.disableThreads();
 compiler.initOptions(compilerOptions);
 return compiler;
}

代码示例来源:origin: samaxes/minify-maven-plugin

externs.addAll(closureConfig.getExterns());
Compiler compiler = new Compiler();
compiler.compile(externs, Lists.newArrayList(input), options);
JSError[] errors = compiler.getErrors();
if (errors.length > 0) {
  StringBuilder msg = new StringBuilder("JSCompiler errors\n");
writer.append(compiler.toSource());
    flushSourceMap(sourceMapResult, minifiedFile.getName(), compiler.getSourceMap());

代码示例来源:origin: org.wisdom-framework/wisdom-maven-plugin

private void compile(File base) throws WatchingException {
  getLog().info("Compressing JavaScript files from " + base.getName() + " using Google Closure");
  PrintStream out = getPrintStreamToDumpLog();
  com.google.javascript.jscomp.Compiler compiler = new com.google.javascript.jscomp.Compiler(out);
  CompilerOptions options = newCompilerOptions();
  getLog().info("Compilation Level set to " + googleClosureCompilationLevel);
  compiler.initOptions(options);
  final Result result = compiler.compile(externs, inputs, options);
  listErrors(result);
  String[] outputs = compiler.toSourceArray();
  File minified;
  for (int i = 0; i < store.size(); i++) {

代码示例来源:origin: org.scala-js/closure-compiler-java-6

private Compiler createCompiler(
  List<SourceFile> inputs, List<SourceFile> externs, CompilerOptions compilerOptions) {
 Compiler compiler = new Compiler();
 compiler.disableThreads();
 compiler.compile(externs, inputs, compilerOptions);
 return compiler;
}

代码示例来源:origin: org.scala-js/closure-compiler-java-6

Compiler.setLoggingLevel(Level.OFF);
   externs.size() + " extern(s)");
 Result result = compiler.compile(externs, sources, options);
  StringBuilder source = new StringBuilder(compiler.toSource());

代码示例来源:origin: org.apache.shindig/shindig-gadgets

private Compiler mockRealJsCompiler(JSError error, Result res, String toSource) {
 Compiler result = createMock(Compiler.class);
 expect(result.compile(EasyMock.<List<JSSourceFile>>anyObject(),
   EasyMock.<List<JSSourceFile>>anyObject(),
   isA(CompilerOptions.class))).andReturn(res);
 if (error != null) {
  expect(result.hasErrors()).andReturn(true);
  expect(result.getErrors()).andReturn(new JSError[] { error });
 } else {
  expect(result.hasErrors()).andReturn(false);
 }
 expect(result.getResult()).andReturn(res);
 expect(result.toSource()).andReturn(toSource);
 replay(result);
 return result;
}

代码示例来源:origin: org.scala-js/closure-compiler-java-6

private static void lint(String filename, boolean fix) throws IOException {
 SourceFile file = SourceFile.fromFile(filename);
 Compiler compiler = new Compiler(System.out);
 CompilerOptions options = new CompilerOptions();
 options.setLanguage(LanguageMode.ECMASCRIPT6_STRICT);
 options.setWarningLevel(DiagnosticGroups.MISSING_REQUIRE, CheckLevel.WARNING);
 options.setWarningLevel(DiagnosticGroups.EXTRA_REQUIRE, CheckLevel.WARNING);
 compiler.setPassConfig(new LintPassConfig(options));
 compiler.disableThreads();
 SourceFile externs = SourceFile.fromCode("<Linter externs>", "");
 compiler.compile(ImmutableList.<SourceFile>of(externs), ImmutableList.of(file), options);
 if (fix) {
  List<SuggestedFix> fixes = new ArrayList<SuggestedFix>();
  for (JSError warning : concat(compiler.getErrors(), compiler.getWarnings(), JSError.class)) {
   SuggestedFix suggestedFix = ErrorToFixMapper.getFixForJsError(warning, compiler);
   if (suggestedFix != null) {

代码示例来源:origin: org.apache.flex.flexjs.compiler/compiler-jx

System.out.println(file.getName());
System.out.println("end of list of source files");
compiler_.compile(jsExternsFiles_, jsSourceFiles_, options_);
  targetFile.write(compiler_.toSource());
  targetFile.close();
  compiler_.getSourceMap().appendTo(sourceMapFile, "");
  sourceMapFile.close();

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

protected Compiler getCompiler() {
  return new Compiler();
}

代码示例来源:origin: org.apache.shindig/shindig-gadgets

public CompileResult(Compiler compiler, Result result) {
 content = compiler.toSource();
 externExport = result.externExport;
}

代码示例来源:origin: com.google.javascript/closure-compiler

/** Compiles a single source file and a single externs file. */
public Result compile(SourceFile extern, SourceFile input, CompilerOptions options) {
 return compile(ImmutableList.of(extern), ImmutableList.of(input), options);
}

代码示例来源:origin: ca.carleton.gcrc/nunaliit2-javascript

Compiler compiler = new Compiler();
Result result = compiler.compile(externs, inputs, compilerOptions);

代码示例来源:origin: apache/royale-compiler

private void initializeCompiler()
{
  jscompiler = new Compiler();
  options = new JXCompilerOptions();
  //options.setLanguageIn(LanguageMode.ECMASCRIPT6_TYPED);
  //options.setLanguageOut(LanguageMode.ECMASCRIPT6_TYPED);
  options.setPreserveTypeAnnotations(true);
  options.setPrettyPrint(true);
  options.setLineLengthThreshold(80);
  options.setPreferSingleQuotes(true);
  //options.setIdeMode(true);
  options.setParseJsDocDocumentation(Config.JsDocParsing.INCLUDE_DESCRIPTIONS_NO_WHITESPACE);
  options.setExternExports(false);
  options.setExtraAnnotationNames(Arrays.asList(asdocTags));
  options.setLanguageIn(LanguageMode.ECMASCRIPT_2015);
  options.setLanguageIn(LanguageMode.ECMASCRIPT5_STRICT);
  options.addCustomPass(CustomPassExecutionTime.BEFORE_OPTIMIZATIONS, new NamespaceResolutionPass(model,
      jscompiler));
  options.addCustomPass(CustomPassExecutionTime.BEFORE_OPTIMIZATIONS, new ResolvePackagesPass(model, jscompiler));
  options.addCustomPass(CustomPassExecutionTime.BEFORE_OPTIMIZATIONS, new CollectTypesPass(model, jscompiler));
  options.addCustomPass(CustomPassExecutionTime.BEFORE_OPTIMIZATIONS, new AddMemberPass(model, jscompiler));
  options.addCustomPass(CustomPassExecutionTime.BEFORE_OPTIMIZATIONS, new CollectImportsPass(model, jscompiler));
  //compiler.setErrorManager(testErrorManager);
  jscompiler.initOptions(options);
  // don't need custom error manager with es6->es5 language options
  //jscompiler.setErrorManager(wrapErrorManager(jscompiler.getErrorManager()));
  model.setJSCompiler(jscompiler);
}

代码示例来源:origin: org.scala-js/closure-compiler-java-6

Compiler.setLoggingLevel(Level.parse(config.loggingLevel));
compiler.initWarningsGuard(options.getWarningsGuard());
List<SourceFile> inputs =
  createSourceInputs(jsModuleSpecs, config.mixedJsSources, jsonFiles);
  compiler.initModules(externs, modules, options);
  compiler.orderInputsWithLargeStack();
 } else {
  result = compiler.compileModules(externs, modules, options);
  compiler.init(externs, inputs, options);
  compiler.orderInputsWithLargeStack();
 } else {
  result = compiler.compile(externs, inputs, options);
 modules = ImmutableList.copyOf(compiler.getDegenerateModuleGraph()
   .getAllModules());
 for (JSModule m : modules) {
 if (compiler.getSourceFileByName(outputFileName) != null) {
  compiler.report(
    JSError.make(OUTPUT_SAME_AS_INPUT_ERROR, outputFileName));
  return 1;

代码示例来源:origin: org.scala-js/closure-compiler-java-6

/**
 * Compiles a list of inputs.
 */
public <T1 extends SourceFile, T2 extends SourceFile> Result compile(
  List<T1> externs, List<T2> inputs, CompilerOptions options) {
 // The compile method should only be called once.
 Preconditions.checkState(jsRoot == null);
 try {
  init(externs, inputs, options);
  if (hasErrors()) {
   return getResult();
  }
  return compile();
 } finally {
  Tracer t = newTracer("generateReport");
  errorManager.generateReport();
  stopTracer(t, "generateReport");
 }
}

代码示例来源:origin: org.scala-js/closure-compiler-java-6

/**
 * Compiles a list of modules.
 */
public <T extends SourceFile> Result compileModules(List<T> externs,
  List<JSModule> modules, CompilerOptions options) {
 // The compile method should only be called once.
 Preconditions.checkState(jsRoot == null);
 try {
  initModules(externs, modules, options);
  if (hasErrors()) {
   return getResult();
  }
  return compile();
 } finally {
  Tracer t = newTracer("generateReport");
  errorManager.generateReport();
  stopTracer(t, "generateReport");
 }
}

代码示例来源:origin: org.apache.flex.flexjs.compiler/compiler-jx

public JSClosureCompilerWrapper(List<String> args)
{
  Compiler.setLoggingLevel(Level.INFO);
  compiler_ = new Compiler();
  ArrayList<String> splitArgs = new ArrayList<String>();
  for (String s : args)
  {
    if (s.contains(" "))
    {
      String[] parts = s.split(" ");
      Collections.addAll(splitArgs, parts);
    }
    else
      splitArgs.add(s);
  }
  String[] stringArgs = new String[splitArgs.size()];
  splitArgs.toArray(stringArgs);
  options_ = new CompilerOptionsParser(stringArgs).getOptions();
  
  jsSourceFiles_ = new ArrayList<SourceFile>();
  jsExternsFiles_ = new ArrayList<SourceFile>();
  
  initOptions(args);
  initExterns();
}

相关文章

Compiler类方法