Параметры компилятора закрытия

Я хочу использовать Closure Compiler для минимизации/сжатия JS-кода.

проблема в том, что он не минимизируется так, как я ожидаю. рассмотрите код ниже. когда я передаю строку

var func = function ( someArgument ) {
  alert ( someArgument ); 
  return someArgument; 
}

Я ожидаю, что минимизированный код переименует «someArgument» во что-то более короткое, например «a».

это так или я что-то не так делаю? ТИА

public static void Compress( String src ) {

    ByteArrayOutputStream err = new ByteArrayOutputStream();

    CompilerOptions opt = new CompilerOptions();

    CompilationLevel.ADVANCED_OPTIMIZATIONS.setDebugOptionsForCompilationLevel( opt );

    Compiler.setLoggingLevel( Level.OFF );
    Compiler compiler = new Compiler( new PrintStream( err ) );
    compiler.disableThreads();

    List<SourceFile> externs = Collections.emptyList();
    List<SourceFile> inputs = Arrays.asList( SourceFile.fromCode( "javascript-code.js", src) );

    Result result = compiler.compile( externs, inputs, opt );

    System.out.println( "source: " + compiler.toSource() );
}

person isapir    schedule 29.01.2013    source источник
comment
Вы пробовали это с помощью инструментов командной строки?   -  person Ja͢ck    schedule 29.01.2013


Ответы (1)


Вы используете setDebugOptionsForCompilationLevel(), вам нужен setOptionsForCompilationLevel(). Из Источника это что делает setDebugOptionsForCompilationLevel:

public void setDebugOptionsForCompilationLevel(CompilerOptions options) {
    options.anonymousFunctionNaming = AnonymousFunctionNamingPolicy.UNMAPPED;
    options.generatePseudoNames = true;
    options.removeClosureAsserts = false;
    // Don't shadow variables as it is too confusing.
    options.shadowVariables = false;
}

Пока это то, что делает setOptionsForCompilationLevel():

// All the safe optimizations.
options.dependencyOptions.setDependencySorting(true);
options.closurePass = true;
options.foldConstants = true;
options.coalesceVariableNames = true;
options.deadAssignmentElimination = true;
options.extractPrototypeMemberDeclarations = true;
options.collapseVariableDeclarations = true;
options.convertToDottedProperties = true;
options.rewriteFunctionExpressions = true;
options.labelRenaming = true;
options.removeDeadCode = true;
options.optimizeArgumentsArray = true;
options.collapseObjectLiterals = true;
options.protectHiddenSideEffects = true;

// All the advance optimizations.
options.removeClosureAsserts = true;
options.aliasKeywords = true;
options.reserveRawExports = true;
options.setRenamingPolicy(
    VariableRenamingPolicy.ALL, PropertyRenamingPolicy.ALL_UNQUOTED);
options.shadowVariables = true;
options.removeUnusedPrototypeProperties = true;
options.removeUnusedPrototypePropertiesInExterns = true;
options.collapseAnonymousFunctions = true;
options.collapseProperties = true;
options.checkGlobalThisLevel = CheckLevel.WARNING;
options.rewriteFunctionExpressions = true;
options.smartNameRemoval = true;
options.inlineConstantVars = true;
options.setInlineFunctions(Reach.ALL);
options.inlineGetters = true;
options.setInlineVariables(Reach.ALL);
options.flowSensitiveInlineVariables = true;
options.computeFunctionSideEffects = true;

// Remove unused vars also removes unused functions.
options.setRemoveUnusedVariables(Reach.ALL);

// Move code around based on the defined modules.
options.crossModuleCodeMotion = true;
options.crossModuleMethodMotion = true;

// Call optimizations
options.devirtualizePrototypeMethods = true;
options.optimizeParameters = true;
options.optimizeReturns = true;
options.optimizeCalls = true;

Технически, SIMPLE_OPTIMIZATIONS даст вам переименование аргумента., в случае, если расширенный запуск вызовет проблемы с вашим кодом (опять же из источника):

/**
 * SIMPLE_OPTIMIZATIONS performs transformations to the input JS that do not
 * require any changes to JS that depend on the input JS. For example,
 * function arguments are renamed (which should not matter to code that
 * depends on the input JS), but functions themselves are not renamed (which
 * would otherwise require external code to change to use the renamed function
 * names).
 */
person Jason Sperske    schedule 29.01.2013
comment
спасибо Джейсон. но когда я устанавливал setDebugOptionsForCompilationLevel(), прежде чем я мог получить минимизированный результат, вызвав компилятор.toSource(), и если я использую setOptionsForCompilationLevel(), я больше не могу этого делать. Любая идея, как я могу получить минимизированный результат? - person isapir; 29.01.2013