{
"compilerOptions": {
"incremental": true.// Incremental compilation
"tsBuildInfoFile": "./buildFile".// Where the incremental compiled file is stored
"diagnostics": true.// Prints compilation information
"target": "es5".// The target language version
"module": "commonjs".// Module standards for generating code
"outFile": "./app.js".// Generate a file from multiple interdependent files that can be used in AMD modules
"lib": [].// Es5 default "dom", "es5", "scripthost"
"allowJs": true.// Allow compiling JS files (JS, JSX)
"checkJs": true.// Allows errors to be reported in JS files, usually with allowJS
"outDir": "./out".// Specify the output directory
"rootDir": ". /".// Specify the input file directory (for output)
"declaration": true.// Generate the declaration file
"declarationDir": "./d".// Declare the path to the file
"emitDeclarationOnly": true.// Only declaration files are generated
"sourceMap": true.// Generate the sourceMap of the target file
"inlineSourceMap": true.// Generate an inline sourceMap for the target file
"declarationMap": true.// Generate the sourceMap for the declaration file
"typeRoots": [].// Declare the file directory, default node_modules/@types
"types": [].// Declare file package
"removeComments": true.// Delete comments
"noEmit": true.// No output file
"noEmitOnError": true.// Do not output files when errors occur
"noEmitHelpers": true./ / not generated helper function, extra install ts - helpers, can also use importHelpers solve at present.
"importHelpers": true.// Introduce helper functions via tslib. The file must be a module
"downlevelIteration": true.// Demote traverser implementation (ES3/5)
"strict": true.// Turn on all strict type checking
"alwaysStrict": false.// inject "use strict" into the code;
"noImplicitAny": false.// Implicit any types are not allowed
"strictNullChecks": false.// It is not allowed to assign null and undefined to other types of variables
"strictFunctionTypes": false.// Bidirectional covariance of function arguments is not allowed
"strictPropertyInitialization": false.Class instance attributes must be initialized
"strictBindCallApply": false.// Strict bind/call/apply check
"noImplicitThis": false.This is not allowed to have an implicit any type
"noUnusedLocals": true.// Check only declared, unused local variables
"noUnusedParameters": true.// Check for unused function arguments
"noFallthroughCasesInSwitch": true.// To prevent switch statements from running through, branches do not break
"noImplicitReturns": true.// Each branch must have a return value
"esModuleInterop": true.// Allow export = export, import from import
"allowUmdGlobalAccess": true.// Allow access to UMD global variables in modules
"moduleResolution": "node".// The module resolves the policy
"baseUrl": ". /".// Resolve the base address of a non-relative module
"paths": {
// Path mapping, relative to baseUrl
"jquery": ["node_modules/jquery/dist/jquery.slim.min.js"]},"rootDirs": ["src"."util"].// Put multiple directories in one virtual directory for use at run time
"listEmittedFiles": true.// Print out the output file
"listFiles": true // Print the compiled file (including the referenced declaration file)}}Copy the code
Incremental compilation (faster compilation)
incremental
The Typescript compiler produces a file that stores compilation information when it is first compiled; The compiler can perform incremental compilation from this file during secondary compilation.
This file will be named tsconfig.tsBuildinfo in the root directory by default
tsBuildInfoFile
You can modify the storage folder and file name of the compiled file.
diagnostics
Prints compilation information.
Use a combination of
{
"compilerOptions": {
"incremental": true.// Incremental compilation
"tsBuildInfoFile": "./buildFile".// Where the incremental compiled file is stored
"diagnostics": true // Prints compilation information}}Copy the code
First compile information:
Files: 113 Lines: 85109 Nodes: 263776 Identifiers: 97483 Symbols: 78297 Types: 26645 Instantiations: 20354 Memory used: 149278K I/O Read: 0.06s I/O Write: 0.00s Parse time: 1.23s Bind time: 0.58s Check time: 2.17s Emit time: 0.04 s Total time: 4.02 sCopy the code
Second compilation information:
Files: 113 Lines: 85109 Nodes: 263776 Identifiers: 97483 Symbols: 59089 Types: 78 Instantiations: 0 Memory used: 99709K I/O Read: 0.09s I/O Write: 0.00s Parse time: 1.58s Bind time: 0.64s Check time: 0.00s Emit time: 0.00 s Total time: 2.22 sCopy the code
Total Time can vary by about 50%.
Target language and module
target
Set the target language to ES3, ES5, ES2015, etc. The default is ES3.
module
Set the module standards for generated code, which can be CommonJS, AMD, UMD, and so on
outFile
Generate a file from multiple interdependent files that can be used in AMD modules
Use a combination of
We create two files:
// ./src/amd.ts
let amd: string[] = ["a"];
export = amd;
Copy the code
// ./src/index.ts
import a = require("./amd");
let hello: string = "Hello TypeScript";
document.querySelectorAll(".app") [0].innerHTML = hello;
Copy the code
{
"compilerOptions": {
"module": "amd"."outFile": "./app.js"}}Copy the code
After compiling, you get an app.js file:
define("amd"["require"."exports"].function (require.exports) {
"use strict";
var amd = ["a"];
return amd;
});
define("index"["require"."exports"].function (require.exports) {
"use strict";
Object.defineProperty(exports."__esModule", { value: true });
var hello = "Hello TypeScript";
document.querySelectorAll(".app") [0].innerHTML = hello;
});
var libs = {};
Copy the code
The class library lib
Specify the library that TS needs to reference, the declaration file.
If target: es5, import the library [” DOM “, “ES5 “, “scripthost”] by default.
Example: If using es2019 methods:
let array = [1.2.3[4.5]].flat();
Copy the code
{
"compilerOptions": {
"lib": ["ES2019.Array"]}}Copy the code
Compiling JS files
allowJS
Allows compilers to compile JS files (JS, JSX).
checkJS
Allows error reporting in JS files, usually with allowJS.
outDir
Specify the output directory.
rootDir
Specifies the input file directory (for output).
Use a combination of
{
"compilerOptions": {
"allowJS": true."checkJS": true}}// ERROR! Cannot write file '/Users/xqq/workspace/qq/code/geekUniversity/TypeScript/ts_in_action/build/webpack.base.config.js' because it would overwrite input file.
Copy the code
Error: The compiler will compile all js files by default, including webpack files under Build. We need include, and the compiled file overwrites the original file, so we also need to specify the output directory.
{
"include": "./src"."compilerOptions": {
"allowJS": true."checkJS": true."outDir": "./out"}}Copy the code
Compiled file directory
|-- out
|-- a.js
|-- index.js
|-- src
|-- a.js
|-- index.ts
Copy the code
If rootDir: ‘./’ is specified, the resulting directory structure is:
|-- out
|-- src
|-- a.js
|-- index.js
Copy the code
Declaration file & sourceMap
declaration
The compiler allows declaration files (.d.ts) to be generated when compiled.
declarationDir
Specifies the directory where the declaration file is generated.
emitDeclarationOnly
Only declaration files are allowed to be generated when the compiler compiles.
sourceMap
When the compiler compiles, it generates the sourceMap file for the target file.
inlineSourceMap
When the compiler compiles, sourceMap is generated in a JS file.
declarationMap
When the compiler compiles, it generates the sourceMap of the declaration file.
typeRoots
The default is node_modules/@types > types. This is the declaration package. If a declaration file is set, the compiler will only load that declaration file.
Use a combination of
-
Generate declaration file
{ "declaration": true.// Generate the declaration file "declarationDir": "./d".// Declare the path to the file "emitDeclarationOnly": true // Only declaration files are generated } Copy the code
After compilation, only the index.d.ts declaration file is generated in the./d folder.
-
SourceMap file
{ "sourceMap": true } Copy the code
After compilation, index.js and index.js.map are generated.
-
InlineSourceMap file
{ "inlineSourceMap": true } Copy the code
After compiling, index.js is generated:
// import a = require("./amd"); var hello = "Hello TypeScript"; document.querySelectorAll(".app") [0].innerHTML = hello; // let array = [1, 2, 3, [4, 5]].flat(); // flat array [1,2,3,4,5] //# sourceMappingURL=data:application/json; base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJpbmRleC50cyJdLCJuYW1lcyI6W10sIm1hc HBpbmdzIjoiQUFBQSwrQkFBK0I7QUFFL0IsSUFBSSxLQUFLLEdBQVcsa0JBQWtCLENBQUM7QUFDdkMsUUFBUSxDQUFDLGdCQUFnQixDQUFDLE1BQU0sQ0FBQ yxDQUFDLENBQUMsQ0FBQyxDQUFDLFNBQVMsR0FBRyxLQUFLLENBQUM7QUFFdkQsNkRBQTZEIn0= Copy the code
-
Declare the sourceMap of the file
{ "declaration": true."declarationMap": true } Copy the code
Js, index.d.ts and index.d.ts are generated after compilation.
Helper function
noEmitHelpers
When set to true, no helper functions are generated.
For example:
class A {}
class B extends A {}
export = A;
Copy the code
The compiled:
"use strict";
var __extends =
(this && this.__extends) ||
(function () {
var extendStatics = function (d, b) {
extendStatics =
Object.setPrototypeOf ||
({ __proto__: []}instanceof Array &&
function (d, b) { d.__proto__ = b; }) | |function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
};
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() {
this.constructor = d;
}
d.prototype =
b === null
? Object.create(b)
: ((__.prototype = b.prototype), new(4)); }; }) ();var B = / * *@class * / (function () {
function B() {}
returnB; }) ();var A = / * *@class * / (function (_super) {
__extends(A, _super);
function A() {
return(_super ! = =null && _super.apply(this.arguments)) || this;
}
return A;
})(B);
module.exports = A;
Copy the code
The compiler automatically generates __extends.
NoEmitHelpers: true if noEmitHelpers: true
"use strict";
var B = / * *@class * / (function () {
function B() {}
returnB; }) ();var A = / * *@class * / (function (_super) {
__extends(A, _super);
function A() {
return(_super ! = =null && _super.apply(this.arguments)) || this;
}
return A;
})(B);
module.exports = A;
Copy the code
The compiled __extends is undefined. Ts defines importHelpers as a configuration item for the developer to solve this problem.
importHelpers
Introduce helper functions via tslib. Files must be modules.
"use strict";
var tslib_1 = require("tslib");
var A = / * *@class * / (function () {
function A() {}
returnA; }) ();var B = / * *@class * / (function (_super) {
tslib_1.__extends(B, _super);
function B() {
return(_super ! = =null && _super.apply(this.arguments)) || this;
}
return B;
})(A);
module.exports = A;
Copy the code
downlevelIteration
Previously iterators were only available when compiling for ES6/ES2015 or later. Also, design the structure of iterator protocols, such as for.. Of, if the compile goal is lower than ES6/ES2015, is only supported when manipulating arrays.
TypeScript 2.3 adds full support for generator and iterator protocols in ES3 and ES5 with the –downlevelIteration option for compilation targets.
With the –downlevelIteration option, the compiler uses the new type checking and output behavior to attempt to call the [symbol.iterator]() method on the iterated object (if any), or to create a semantic array iterator on the object.
Note that this requires non-array values to have either a native symbol. iterator or a run-time mock implementation of symbol. iterator.
With –downlevelIteration, in ES5/ES3 for.. Of statements, array deconstruction, array expansion, function calls, and new expressions are available when symbol. iterator is supported, but can be used on arrays at runtime or at development time even if symbol. iterator is not defined.
// index.ts
let a = [1.2.3];
let b = [1. a];Copy the code
// downlevelIteration: false
var __spreadArray =
(this && this.__spreadArray) ||
function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
var a = [1.2.3];
var b = __spreadArray([1], a);
Copy the code
// downlevelIteration: true
var __read =
(this && this.__read) ||
function (o, n) {
var m = typeof Symbol= = ="function" && o[Symbol.iterator];
if(! m)return o;
var i = m.call(o),
r,
ar = [],
e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
ar.push(r.value);
} catch (error) {
e = { error: error };
} finally {
try {
if(r && ! r.done && (m = i["return"])) m.call(i);
} finally {
if (e) throwe.error; }}return ar;
};
var __spreadArray =
(this && this.__spreadArray) ||
function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
var a = [1.2.3];
var b = __spreadArray([1], __read(a));
Copy the code
Strict mode
strict
Indicates that strict type checking is enabled. If strict is true, AlwaysStrict, noImplicitAny, strictNullChecks, strictFunctionTypes, strictPropertyInitialization, strictBindCallApply and The noImplicitThis option defaults to true.
strictNullChecks
Null and undefined are not allowed to be assigned to variables of other types.
// strictNullChecks: false
let a: number = 1;
a = null; // OK
a = undefined; // OK
Copy the code
strictFunctionTypes
Bidirectional covariance of function parameters is not allowed.
// strictFunctionTypes: false
interface point2D {
x: number;
y: number;
}
interface point3D {
x: number;
y: number;
z: number;
}
let p2d = (value: point2D) = > {};
let p3d = (value: point3D) = > {};
p3d = p2d;
p2d = p3d; // OK
Copy the code
strictBindCallApply
Strict bind, call, apply checks.
// strictvindCallApply: true
function add(a: number, b: number) {
return a + b;
}
add.call(undefined.1."2"); // Error!
Copy the code
// strictvindCallApply: false
function add(a: number, b: number) {
return a + b;
}
add.call(undefined.1."2"); // OK!
Copy the code
noImplicitThis
This is not allowed to have an implicit any type.
// noImplicitThis: true
class A {
a: number = 1;
getA() {
return function () {
console.log(this.a); // ERROR}; }}new A().getA()(); // Uncaught TypeError: Cannot read property 'a' of undefined
Copy the code
class A {
a: number = 1;
getA() {
return () = > {
console.log(this.a); // OK}; }}Copy the code
The module
esModuleInterop
Export = is allowed, and import = is allowed.
// a.ts
let a: number = 1;
export = a;
Copy the code
// esModuleInterop: false
import a from "./a";
// ERROR: import a require('./a')
Copy the code
allowUmdGlobalAccess
Allows us to access the UMD module as a global variable within the module.
moduleResolution
There are two parsing policies: Node and Classic. Ts uses node parsing by default.
-
The Classic module resolution strategy is applicable to AMD, System, and ES2015.
-
When imported in relative mode, ts parses. Ts and. D. ts files in the same directory.
// /root/src/moduleA.ts import { b } from "./moduleB"; /** * /root/src/moduleB.ts * /root/src/moduleB.d.ts */ Copy the code
-
When imported in a non-relative manner, ts looks for node_modules in the current directory. If not found, ts looks for the higher directory in turn.
// /root/src/moduleA.ts import { b } from "moduleB"; /** * /root/src/node_modules/moduleB.ts * /root/src/node_modules/moduleB.d.ts * * /root/node_modules/moduleB.ts * /root/node_modules/moduleB.d.ts * * /node_modules/moduleB.ts * /node_modules/moduleB.d.ts */ Copy the code
-
-
The Node module parses the policy
-
Relative mode import
// /root/src/moduleA.ts import { b } from "./moduleB"; / * * * / root/SRC/moduleB ts * / root/SRC/moduleB TSX * / root/SRC/moduleB which s * / root/SRC/moduleB/package. The json (types properties) * /root/src/moduleB/index.ts * /root/src/moduleB/index.tsx * /root/src/moduleB/index.d.ts */ Copy the code
-
Non-relative import
// /root/src/moduleA.ts import { b } from "moduleB"; /** * /root/src/node_modules/moduleB.ts * /root/src/node_modules/moduleB.tsx * /root/src/node_modules/moduleB.d.ts * Json (" types "attribute) * /root/src/node_modules/index.ts * /root/src/node_modules/index.tsx * Ts * * Look up the directory * * /root/node_modules/ moduleb.ts * /root/node_modules/ moduleb.tsx * Ts * /root/node_modules/ moduleb.d. ts * /root/node_modules/package.json (" types "attribute) * /root/node_modules/index.ts * /root/node_modules/index.tsx * /root/node_modules/index.d.ts * * /node_modules/moduleB.ts * /node_modules/moduleB.tsx * Ts * /node_modules/ moduleb.d. ts * /node_modules/package.json (" types "attribute) * /node_modules/index.ts * /node_modules/index.tsx * /node_modules/index.d.ts */ Copy the code
-
baseUrl
Resolves the base address of a non-relative module, which defaults to the current directory
paths
Path mapping, as opposed to baseUrl. For example, if you want to introduce a simplified version of jquery, you can specify its relative path.
{
"compilerOptions": {
"paths": {
// Path mapping, relative to baseUrl
"jquery": ["node_modules/jquery/dist/jquery.slim.min.js"]}}}Copy the code
RootDirs (different from rootDir)
Put multiple directories in a single virtual directory for use at run time.
// ./tsconfig.json
{
"compilerOptions": {
"rootDirs": ["src"."out"]}}Copy the code
Create a new out directory to store the files after the build.
// ./out/util.ts
let a: number = 1;
export = a;
Copy the code
After the build, index will also be put into the out directory. In order not to need to change the path after compiling, we can virtualize them in a directory in advance.
// ./src/index.ts
import a require("./util")
Copy the code
Note that when a is introduced, it is the current directory that is introduced. Because when rootDirs sets SRC and out directories, the compiler defaults them to sibling directories.
The TypeScript project family
- Don’t use TypeScript? Namespace.
- TS effort: declared merger
- How do I introduce external class libraries into TypeScript?
- Get started, tsconfig (file options)
- Get started, tsconfig (compilation option)
- Would you like to learn a more efficient way to build TS (engineering introduction)
- TS compiler! From ts – loader to Babel
- Code check tool! From TSLint to ESLint
- TS single test tool! Ts – jest and Babel/jest