6

Sto provando Google Closure, in particolare le annotazioni per rafforzare la sicurezza dei tipi. Per eseguire il test che ho fatto qualcosa di sbagliato, anche se il compilatore non mi dirà che si tratta di ...Google Closure Annotating non mi dirà che ho torto

Ecco il codice:

// ==ClosureCompiler== 
// @output_file_name default.js 
// @compilation_level SIMPLE_OPTIMIZATIONS 
// ==/ClosureCompiler== 

/** 
* A card. 
* @constructor 
* @param {String} cardName The exact name of the card 
* @param {Kinetic.Layer} layer The layer for the card 
*/ 
function CardObject(cardName, layer) 
{ 
    /** @type {Number} */ 
    var number = cardName; 
} 

Così, ho una variabile number che io dico è un Number, e provo ad assegnare una stringa ad esso. Questo non dovrebbe essere possibile, giusto? Anche se il compilatore non mi dirà che ...

Perché non mi dice che è sbagliato?

risposta

7

Chiusura compilatore utilizza warning levels per determinare quali controlli sono abilitati durante il processo di compilazione. I tre livelli di allarme sono:

  • TRANQUILLA
  • DI DEFAULT
  • VERBOSE

Ad esempio, utilizzando il livello di compilazione SIMPLE_OPTIMIZATIONS, si continua a ottenere tipo-check avvisi con il livello di allarme impostato VERBOSE .

// ==ClosureCompiler== 
// @output_file_name default.js 
// @compilation_level SIMPLE_OPTIMIZATIONS 
// @warning_level VERBOSE 
// ==/ClosureCompiler== 

/** 
* A card. 
* @constructor 
* @param {String} cardName The exact name of the card 
* @param {Kinetic.Layer} layer The layer for the card 
*/ 
function CardObject(cardName, layer) 
{ 
    /** @type {Number} */ 
    var number = cardName; 
} 

uscita

Number of warnings: 2 

JSC_TYPE_PARSE_ERROR: Bad type annotation. Unknown type Kinetic.Layer at line 5 
character 10 
* @param {Kinetic.Layer} layer The layer for the card 
     ^
JSC_TYPE_MISMATCH: initializing variable 
found : (String|null|undefined) 
required: (Number|null) at line 10 character 13 
var number = cardName; 
      ^

per capire esattamente quali controlli sono associati ad ogni livello di allarme, ecco il codice corrispondente da WarningLevels.java.

TRANQUILLA

/** 
* Silence all non-essential warnings. 
*/ 
private static void silenceAllWarnings(CompilerOptions options) { 
    // Just use a ShowByPath warnings guard, so that we don't have 
    // to maintain a separate class of warnings guards for silencing warnings. 
    options.addWarningsGuard(
     new ShowByPathWarningsGuard(
      "the_longest_path_that_cannot_be_expressed_as_a_string")); 

    // Allow passes that aren't going to report anything to be skipped. 

    options.checkRequires = CheckLevel.OFF; 
    options.checkProvides = CheckLevel.OFF; 
    options.checkMissingGetCssNameLevel = CheckLevel.OFF; 
    options.aggressiveVarCheck = CheckLevel.OFF; 
    options.checkTypes = false; 
    options.setWarningLevel(DiagnosticGroups.CHECK_TYPES, CheckLevel.OFF); 
    options.checkUnreachableCode = CheckLevel.OFF; 
    options.checkMissingReturn = CheckLevel.OFF; 
    options.setWarningLevel(DiagnosticGroups.ACCESS_CONTROLS, CheckLevel.OFF); 
    options.setWarningLevel(DiagnosticGroups.CONST, CheckLevel.OFF); 
    options.setWarningLevel(DiagnosticGroups.CONSTANT_PROPERTY, CheckLevel.OFF); 
    options.checkGlobalNamesLevel = CheckLevel.OFF; 
    options.checkSuspiciousCode = false; 
    options.checkGlobalThisLevel = CheckLevel.OFF; 
    options.setWarningLevel(DiagnosticGroups.GLOBAL_THIS, CheckLevel.OFF); 
    options.setWarningLevel(DiagnosticGroups.ES5_STRICT, CheckLevel.OFF); 
    options.checkCaja = false; 
} 

DI DEFAULT

/** 
* Add the default checking pass to the compilation options. 
* @param options The CompilerOptions object to set the options on. 
*/ 
private static void addDefaultWarnings(CompilerOptions options) { 
    options.checkSuspiciousCode = true; 
    options.checkUnreachableCode = CheckLevel.WARNING; 
    options.checkControlStructures = true; 
} 

VERBOSE

/** 
* Add all the check pass that are possibly relevant to a non-googler. 
* @param options The CompilerOptions object to set the options on. 
*/ 
private static void addVerboseWarnings(CompilerOptions options) { 
    addDefaultWarnings(options); 

    // checkSuspiciousCode needs to be enabled for CheckGlobalThis to get run. 
    options.checkSuspiciousCode = true; 
    options.checkGlobalThisLevel = CheckLevel.WARNING; 
    options.checkSymbols = true; 
    options.checkMissingReturn = CheckLevel.WARNING; 

    // checkTypes has the side-effect of asserting that the 
    // correct number of arguments are passed to a function. 
    // Because the CodingConvention used with the web service does not provide a 
    // way for optional arguments to be specified, these warnings may result in 
    // false positives. 
    options.checkTypes = true; 
    options.checkGlobalNamesLevel = CheckLevel.WARNING; 
    options.aggressiveVarCheck = CheckLevel.WARNING; 
    options.setWarningLevel(
     DiagnosticGroups.MISSING_PROPERTIES, CheckLevel.WARNING); 
    options.setWarningLevel(
     DiagnosticGroups.DEPRECATED, CheckLevel.WARNING); 
} 

noti che options.checkTypes = true; è impostato solo per il livello di avviso VERBOSE. Come indicato da , il controllo del tipo è abilitato anche quando si utilizza il livello di compilazione ADVANCED_OPTIMIZATIONS.

Inoltre, le classi di avvertimenti possono essere controllati individualmente con l'applicazione Closure Compiler (file jar) utilizzando flag di compilazione:

  • --jscomp_off
  • --jscomp_warning
  • --jscomp_error

Le classi di avvertenza che possono essere specificate sono le seguenti:

  • accessControls
  • ambiguousFunctionDecl
  • checkRegExp
  • checkTypes
  • checkVars
  • const
  • constantProperty
  • sconsigliata
  • duplicateMessage
  • es5Strict
  • 012.351.641,061 mila
  • externsValidation
  • fileoverviewTags
  • globalThis
  • internetExplorerChecks
  • invalidCasts
  • missingProperties
  • nonStandardJsDocs
  • strictModuleDepCheck
  • typeInvalidation
  • undefinedNames
  • undefinedVars
  • unknownDefines
  • uselessCode
  • visibilità

Ad esempio, digitare le avvertenze di controllo potrebbero essere abilitati singolarmente:

--jscomp_warning=checkTypes 
+0

Ok, questa è una risposta incredibile. Grazie, ho imparato molto e ora posso usare l'ottimizzazione semplice con controllo del tipo: D Grazie! –

0

si deve solo selezionare la modalità di ottimizzazione avanzata:

// @compilation_level ADVANCED_OPTIMIZATIONS 

Poi per questo codice, ad esempio:

// ==ClosureCompiler== 
// @output_file_name default.js 
// @compilation_level ADVANCED_OPTIMIZATIONS 
// ==/ClosureCompiler== 

/** 
* @param {String} str 
*/ 
function func(str) { 
    /** @type {Number} */ 
    var num = str; 
} 

Ci saranno Attenzione:

JSC_TYPE_MISMATCH: initializing variable 
found : (String|null) 
required: (Number|null) at line 6 character 10 
var num = str; 

penso che tu sappia, ma se no, puoi giocare online qui: http://closure-compiler.appspot.com/home

+0

Hmm, si sono totalmente ragione. C'è una ragione per cui non esegue il controllo nella semplice ottimizzazione? Poiché avanzato è un po 'troppo aggressivo per i miei gusti. Ho più file js e i nomi delle modifiche avanzate delle funzioni apparentemente (ho appena iniziato ad usare le cose di chiusura, quindi potrebbe essere sbagliato) –

+0

Ho appena provato a compilare il mio Card.js (che contiene il mio oggetto oggetti di carta) con l'ottimizzazione avanzata, e lo compila via. Prendo un file vuoto, presumo perché non riesce a trovare che sia usato ovunque. Ma è usato, solo in un altro file js ... –

+0

Sto usando il file jar, chiamato da Notepad ++: "java -jar" C: \ Users \ Pablo \ Documents \ Google Closure \ compiler.jar "- -js "$ (FULL_CURRENT_PATH)" --js_output_file "$ (FULL_CURRENT_PATH) .compiled" --compilation_level ADVANCED_OPTIMATIONS " –

Problemi correlati