Zoeken…


Syntaxis

  • Gebruikt JSON-bestandsindeling
  • Kan ook opmerkingen in JavaScript-stijl accepteren

Opmerkingen

Overzicht

De aanwezigheid van een tsconfig.json-bestand in een map geeft aan dat de map de root is van een TypeScript-project. Het bestand tsconfig.json geeft de rootbestanden en de compileropties aan die nodig zijn om het project te compileren.

Tsconfig.json gebruiken

  • Door tsc zonder invoerbestanden aan te roepen, in welk geval de compiler zoekt naar het bestand tsconfig.json beginnend in de huidige map en doorgaand naar de bovenliggende mapketen.
  • Door tsc aan te roepen zonder invoerbestanden en een opdrachtregeloptie --project (of alleen -p) die het pad aangeeft van een map met een bestand tsconfig.json. Wanneer invoerbestanden worden opgegeven op de opdrachtregel, zijn tsconfig.json-bestanden dat

Details

De eigenschap "compilerOptions" kan worden weggelaten, in welk geval de standaardwaarden van de compiler worden gebruikt. Bekijk onze volledige lijst met ondersteunde compileropties .

Als er in een tsconfig.json geen eigenschap "files" aanwezig is, neemt de compiler standaard alle TypeScript-bestanden (* .ts of * .tsx) op in de map en de submappen die deze bevatten. Wanneer een eigenschap "bestanden" aanwezig is, worden alleen de opgegeven bestanden opgenomen.

Als de eigenschap "exclude" is opgegeven, bevat de compiler alle TypeScript-bestanden (* .ts of * .tsx) in de map en submappen met uitzondering van de bestanden of mappen die zijn uitgesloten.

De eigenschap "files" kan niet worden gebruikt in combinatie met de eigenschap "exclude". Als beide zijn opgegeven, heeft de eigenschap "bestanden" voorrang.

Bestanden waarnaar wordt verwezen door de bestanden die zijn opgegeven in de eigenschap "files" zijn ook inbegrepen. Evenzo, als naar een bestand B.ts wordt verwezen door een ander bestand A.ts, dan kan B.ts niet worden uitgesloten, tenzij het verwijzende bestand A.ts ook is gespecificeerd in de lijst "uitsluiten".

Een tsconfig.json bestand mag volledig leeg zijn, dat alle bestanden in de bevattende map en submappen compileert met de standaard compileropties.

Compileropties die op de opdrachtregel zijn opgegeven, vervangen de opties die zijn opgegeven in het bestand tsconfig.json.

Schema

Schema is te vinden op: http://json.schemastore.org/tsconfig

Maak een TypeScript-project met tsconfig.json

De aanwezigheid van een tsconfig.json- bestand geeft aan dat de huidige map de root is van een TypeScript-project.

Het initialiseren van een TypeScript-project, of beter gezegd het bestand tsconfig.json, kan worden gedaan met de volgende opdracht:

tsc --init

Vanaf TypeScript v2.3.0 en hoger maakt dit standaard de volgende tsconfig.json:

{
  "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. */
  }
}

De meeste, zo niet alle, opties worden automatisch gegenereerd, waarbij alleen de noodzakelijke benodigdheden niet worden weggelaten.

Oudere versies van TypeScript, zoals bijvoorbeeld v2.0.x en lager, zouden een tsconfig.json als volgt genereren:

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

compileOnSave

compileOnSave signalen instellen op het hoogste niveau om alle bestanden voor een bepaalde tsconfig.json te genereren bij het opslaan.

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

Deze functie is beschikbaar vanaf TypeScript 1.8.4 en hoger, maar moet rechtstreeks worden ondersteund door IDE's. Momenteel zijn voorbeelden van ondersteunde IDE's:

Comments

Een tsconfig.json-bestand kan zowel regel- als blokopmerkingen bevatten, met dezelfde regels als 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 */

Configuratie voor minder programmeerfouten

Er zijn zeer goede configuraties om typen te forceren en meer nuttige fouten te krijgen die niet standaard worden geactiveerd.

{
  "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.
  }
}

Niet genoeg? Als je een harde coder bent en meer wilt, dan ben je misschien geïnteresseerd om je TypeScript-bestanden met tslint te controleren voordat je het compileert met tsc. Controleer hoe tslint te configureren voor nog strengere code .

preserveConstEnums

Typescript ondersteunt kostbare const enum , aangegeven via const enum .

Dit is meestal gewoon syntaxisuiker, omdat de kostbare enums zijn gecompileerd in gecompileerde JavaScript.

Bijvoorbeeld de volgende code

const enum Tristate {
    True,
    False,
    Unknown
}

var something = Tristate.True;

compileert naar

var something = 0;

Hoewel de prestaties profiteren van inlining, kunt u ervoor kiezen om enums te behouden, zelfs als dat kostbaar is (dat wil zeggen: u wilt leesbaarheid op ontwikkelingscode), om dit te doen moet u in tsconfig.json de preserveConstEnums clausole in de compilerOptions op true .

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

Op deze manier zou het vorige voorbeeld worden gecompileerd als alle andere enums, zoals getoond in het volgende fragment.

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
Licentie onder CC BY-SA 3.0
Niet aangesloten bij Stack Overflow