Ricerca…


Sintassi

  • Utilizza il formato di file JSON
  • Può anche accettare commenti di stile JavaScript

Osservazioni

Panoramica

La presenza di un file tsconfig.json in una directory indica che la directory è la radice di un progetto TypeScript. Il file tsconfig.json specifica i file root e le opzioni del compilatore richieste per compilare il progetto.

Utilizzando tsconfig.json

  • Invocando tsc senza file di input, nel qual caso il compilatore cerca il file tsconfig.json che inizia nella directory corrente e continua fino alla catena di directory padre.
  • Richiamando tsc senza file di input e un'opzione della riga di comando --project (o solo -p) che specifica il percorso di una directory contenente un file tsconfig.json. Quando i file di input sono specificati sulla riga di comando, i file tsconfig.json sono

Dettagli

La proprietà "compilerOptions" può essere omessa, nel qual caso vengono utilizzate le impostazioni di default del compilatore. Consulta l'elenco completo delle opzioni del compilatore supportate.

Se non è presente alcuna proprietà "files" in un file tsconfig.json, il compilatore imposta automaticamente tutti i file TypeScript (* .ts o * .tsx) nella directory e nelle sottodirectory contenenti. Quando è presente una proprietà "file", vengono inclusi solo i file specificati.

Se viene specificata la proprietà "exclude" , il compilatore include tutti i file TypeScript (* .ts o * .tsx) nella directory e nelle sottodirectory contenenti, ad eccezione di quei file o cartelle esclusi.

La proprietà "files" non può essere utilizzata insieme alla proprietà "exclude". Se vengono specificati entrambi, la proprietà "files" ha la precedenza.

Sono inclusi anche tutti i file a cui fanno riferimento quelli specificati nella proprietà "files" . Allo stesso modo, se un file B.ts è referenziato da un altro file A.ts, allora B.ts non può essere escluso a meno che il file di riferimento A.ts sia specificato anche nell'elenco "exclude".

Un file tsconfig.json può essere completamente vuoto, che compila tutti i file nella directory e nelle sottodirectory contenenti le opzioni di compilazione predefinite.

Le opzioni del compilatore specificate nella riga di comando sostituiscono quelle specificate nel file tsconfig.json.

Schema

Lo schema può essere trovato su: http://json.schemastore.org/tsconfig

Creare un progetto TypeScript con tsconfig.json

La presenza di un file tsconfig.json indica che la directory corrente è la radice di un progetto abilitato per TypeScript.

L'inizializzazione di un progetto TypeScript, o meglio il file tsconfig.json, può essere effettuata tramite il seguente comando:

tsc --init

A partire da TypeScript v2.3.0 e versioni successive questo creerà il seguente tsconfig.json di default:

{
  "compilerOptions": {
    /* Basic Options */                       
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'. */
    // "lib": [],                             /* Specify library files to be included in the compilation:  */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    // "outDir": "./",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
                                              
    /* Strict Type-Checking Options */        
    "strict": true                            /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */
                                              
    /* Additional Checks */                   
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */
                                              
    /* Module Resolution Options */           
    // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
                                              
    /* Source Map Options */                  
    // "sourceRoot": "./",                    /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "./",                       /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
                                              
    /* Experimental Options */                
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
  }
}

La maggior parte, se non tutte, le opzioni vengono generate automaticamente con le sole necessità lasciate senza commento.

Versioni precedenti di TypeScript, come ad esempio v2.0.xe versioni precedenti, genererebbero tsconfig.json in questo modo:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "sourceMap": false
    }
}

compileOnSave

Impostare una proprietà di livello superiore compileOnSave segnala all'IDE di generare tutti i file per un dato tsconfig.json al momento del salvataggio.

{
    "compileOnSave": true,
    "compilerOptions": {
        ...
    },
    "exclude": [
        ...
    ]
}

Questa funzione è disponibile da TypeScript 1.8.4 in poi, ma deve essere supportata direttamente dagli IDE. Attualmente, esempi di IDE supportati sono:

Commenti

Un file tsconfig.json può contenere sia commenti di riga che di blocco, utilizzando le stesse regole di ECMAScript.

//Leading comment
{
    "compilerOptions": {
        //this is a line comment
        "module": "commonjs", //eol line comment
        "target" /*inline block*/ : "es5",
        /* This is a
        block
        comment */
    }
}
/* trailing comment */

Configurazione per meno errori di programmazione

Ci sono ottime configurazioni per forzare le tipizzazioni e ottenere più errori utili che non sono attivati ​​di default.

{
  "compilerOptions": {

    "alwaysStrict": true, // Parse in strict mode and emit "use strict" for each source file. 

    // If you have wrong casing in referenced files e.g. the filename is Global.ts and you have a /// <reference path="global.ts" /> to reference this file, then this can cause to unexpected errors. Visite: http://stackoverflow.com/questions/36628612/typescript-transpiler-casing-issue
    "forceConsistentCasingInFileNames": true, // Disallow inconsistently-cased references to the same file.

    // "allowUnreachableCode": false, // Do not report errors on unreachable code. (Default: False)
    // "allowUnusedLabels": false, // Do not report errors on unused labels. (Default: False)

    "noFallthroughCasesInSwitch": true, // Report errors for fall through cases in switch statement.
    "noImplicitReturns": true, // Report error when not all code paths in function return a value.

    "noUnusedParameters": true, // Report errors on unused parameters.
    "noUnusedLocals": true, // Report errors on unused locals.

    "noImplicitAny": true, // Raise error on expressions and declarations with an implied "any" type.
    "noImplicitThis": true, // Raise error on this expressions with an implied "any" type.

    "strictNullChecks": true, // The null and undefined values are not in the domain of every type and are only assignable to themselves and any.

    // To enforce this rules, add this configuration.
    "noEmitOnError": true     // Do not emit outputs if any errors were reported.
  }
}

Non abbastanza? Se sei un programmatore hard e vuoi di più, allora potresti essere interessato a controllare i tuoi file TypeScript con tslint prima di compilarlo con tsc. Controlla come configurare tslint per un codice ancora più rigido .

preserveConstEnums

Typescript supporta enumerables costant, dichiarati tramite const enum .

Questo è solitamente solo lo zucchero di sintassi poiché le enumerazioni costanti sono inline nel JavaScript compilato.

Ad esempio il seguente codice

const enum Tristate {
    True,
    False,
    Unknown
}

var something = Tristate.True;

compila a

var something = 0;

Anche se il beneficio perfomance da inline, si può scegliere di mantenere le enumerazioni, anche se costante (ad esempio: si potrebbe desiderare la leggibilità sul codice di sviluppo), per fare questo è necessario impostare in tsconfig.json le preserveConstEnums clausole nelle compilerOptions a true .

{
    "compilerOptions": {
        "preserveConstEnums" = true,
        ...
    },
    "exclude": [
        ...
    ]
}

In questo modo l'esempio precedente verrebbe compilato come qualsiasi altra enumerazione, come mostrato nel seguente frammento.

var Tristate;
(function (Tristate) {
    Tristate[Tristate["True"] = 0] = "True";
    Tristate[Tristate["False"] = 1] = "False";
    Tristate[Tristate["Unknown"] = 2] = "Unknown";
})(Tristate || (Tristate = {}));

var something = Tristate.True


Modified text is an extract of the original Stack Overflow Documentation
Autorizzato sotto CC BY-SA 3.0
Non affiliato con Stack Overflow