In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "how to understand tsconfig.json". In the operation of actual cases, many people will encounter such a dilemma. Then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
A brief introduction to tsconfig.json
1. What is tsconfig.json?
TypeScript uses the tsconfig.json file as its configuration file, and when a tsconfig.json file exists in a directory, it is considered to be the root of the TypeScript project.
Usually, the tsconfig.json file consists of two main parts: specifying the file to be compiled and defining compilation options.
As you can see from the JSON mode of the configuration file of the TypeScript compiler, the tsconfig.json file currently has the following top-level properties:
CompileOnSave
CompilerOptions
Exclude
Extends
Files
Include
References
TypeAcquisition
Some common attribute configurations are described in detail later in the article.
two。 Why use tsconfig.json
Usually we can use the tsc command to compile a small number of TypeScript files:
/ * Parameter description:-- outFile / / File name generated after compilation-- target / / specify the target version of ECMAScript-- module / / specify which module system code index.ts / / source file * / $tsc-- outFile leo.js-- target es3-- module amd index.ts
But if the actual development of the project, rarely only a single file, when we need to compile the entire project, we can use the tsconfig.json file, we need to use the configuration will be written into the tsconfig.json file, so that each compilation does not have to manually enter the configuration, but also convenient for team development.
Second, use tsconfig.json
Currently, there are two operations for using tsconfig.json:
1. Initialize tsconfig.json
There are also two ways to initialize the operation:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Manually create a tsconfig.json file in the project root (or other) and fill in the configuration
Initialize the tsconfig.json file with tsc-- init.
two。 Specify the directory to be compiled
Execute the tsc command without specifying an input file, compile all .ts files from the current directory by default, find the tsconfig.json file from the current directory, and search the parent directory step by step.
$tsc
Alternatively, you can specify the parameter-project or-p for the tsc command to specify the directory to be compiled, which needs to contain a tsconfig.json file, such as:
/ * File directory: ├─ src/ │ ├─ index.ts │ └─ tsconfig.json ├─ package.json * / $tsc-- project src
Note that the command line option for tsc takes precedence and overrides the option of the same name in tsconfig.json.
For more tsc compilation options, see the "compilation options" section.
Third, use examples
In this chapter, we will learn to implement a simple configuration through a small local project, learnTsconfig.
Current development environment: windows / node 10.15.1 / TypeScript3.9
1. Initialize the learnTsconfig project
Execute the following command:
$mkdir learnTsconfig $cd.\ learnTsconfig\ $mkdir src $new-item index.ts
And we write some simple code for the index.ts file:
/ / returns the current version number function getVersion (version:string = "1.0.0"): string {return version;} console.log (getVersion ("1.0.1"))
We will get a directory structure like this:
└─ src/ └─ index.ts
two。 Initialize the tsconfig.json file
Execute from the learnTsconfig root directory:
$tsc-init
3. Modify the tsconfig.json file
We set up several common configuration items:
{"compilerOptions": {"target": "ES5", / / version of the target language "module": "commonjs", / / specify the template standard "noImplicitAny": true, / / the implicit any type "removeComments": true, / / delete the comment "preserveConstEnums": true / / keep the const and enum declaration "sourceMap": true / / generate the sourceMap file of the target file}, "files": [/ / specify the file to be compiled ". / src/index.ts"]}
There is one thing to note:
The files configuration item value is an array that specifies the file to be compiled, that is, the entry file.
When the import file depends on other files, there is no need to specify the dependent files into files, because the compiler will automatically summarize all dependent files into compiled objects, that is, when index.ts depends on user.ts, there is no need to specify user.ts in files, user.ts will be automatically included in the compiled file.
4. Perform compilation
After the configuration is completed, we can execute the tsc command on the command line. After the compilation is completed, we can get an index.js file and an index.js.map file, which proves that we have compiled successfully. The contents of the index.js file are as follows:
Function getVersion (version) {if (version = void 0) {version = "1.0.0";} return version;} console.log (getVersion ("1.0.1")); / / # sourceMappingURL=index.js.map
As you can see, the removeComments configuration in tsconfig.json takes effect, removing the comment code we added.
At this point, you have completed this simple example, and then we will explain "7. Common configuration examples" based on this sample code.
IV. Introduction of tsconfig.json file structure
1. Classified by top-level attribute
The tsconfig.json file is divided into the following categories according to the top-level attributes:
two。 Classify by function
V. introduction to tsconfig.json configuration
1. CompileOnSave
The function of the compileOnSave property is to set automatic compilation when the file is saved, but requires compiler support.
{/ /... "compileOnSave": false,}
2. CompilerOptions
The compilerOptions property is used to configure compilation options.
If the compilerOptions attribute is ignored, the compiler uses the default value and can view the "official complete list of compilation options".
The compilation option configuration is very complex, there are many configurations, and only the commonly used configurations are listed here.
{/ /... "compilerOptions": {"incremental": true, / / the TS compiler generates a file that stores compilation information after the first compilation, and the second compilation will compile incrementally on the basis of the first compilation Can improve the compilation speed "tsBuildInfoFile": ". / buildFile", / / the location where incremental compilation files are stored "diagnostics": true, / / print diagnostic information "target": "ES5", / / target language version "module": "CommonJS", / / template standard for code generation "outFile": ". / app.js" / / generate multiple interdependent files into one file Can be used in the AMD module, that is, set "module": "AMD", "lib": ["DOM", "ES2015", "ScriptHost", "ES2019.Array"], / / the libraries to be referenced by TS, that is, declaration files. Es5 references dom, es5 and scripthost by default. If you need to use the advanced version features of es, you usually need to configure For example, the new array feature of es8 requires the introduction of "ES2019.Array", "allowJS": true, / / allows the compiler to compile the JS,JSX file "checkJs": true, / / allows errors to be reported in JS files, usually uses "outDir": ". / dist" with allowJS, / / specifies the output directory "rootDir": ". /", / / specifies the output file directory (for output) It is used to control the output directory structure "declaration": true, / / generate the declaration file, and automatically generate the declaration file "declarationDir": ". / file", / / specify the directory where the generation declaration file is stored, "emitDeclarationOnly": true, / / only generate declaration files. Instead of generating the js file "sourceMap": true, / / generating the sourceMap file of the target file "inlineSourceMap": true, / / generating the inlineSourceMap of the target file, inlineSourceMap will be included in the generated js file "declarationMap": true, / / generate sourceMap "typeRoots" for the declaration file: [], / / declare the file directory By default, node_modules/@types "types": [], / / loaded declaration package "removeComments": true, / / delete comments "noEmit": true, / / do not output files, that is, no js files "noEmitOnError": true, / / No output files "noEmitHelpers": true, / / No helper function is generated when sending errors, reducing the size If additional installation is required, "importHelpers": true is often used with importHelpers, / / the helper function is introduced through tslib. The file must be implemented by module "downlevelIteration": true, / / degraded traversal, if the target source is es3/5. Then the traversal will have a degraded implementation "strict": true, / / turn on all strict type checking "alwaysStrict": true, / / inject 'use strict' "noImplicitAny": true "into the code, / / do not allow implicit any types" strictNullChecks ": true, / / do not allow assignment of null and undefined to other types of variables" strictFunctionTypes ": true The instance property of the class must initialize "strictBindCallApply": true, / / strict bind/call/apply check "noImplicitThis": true, / / do not allow this to have an implicit any type "noUnusedLocals": true, / / check only declared, unused local variables "noUnusedParameters": true / / check unused function parameters (only prompt no errors) "noFallthroughCasesInSwitch": true, / / prevent switch statements from running through (that is, they will not be executed if there is no break statement) "noImplicitReturns": true, / / each branch will have a return value of "esModuleInterop": true, / / allow export= to export Import "allowUmdGlobalAccess": true by import from, / / allow access to umd module "moduleResolution": "node", / / module parsing policy in the form of global variables in the module. Ts defaults to node parsing policy, that is, relative import of "baseUrl": ". /", / / resolves the base address of non-relative modules. The default is the current directory "paths": {/ / path mapping. Relative to baseUrl / / if you do not want to use the default version when using jq, but need to specify the version manually, you can configure "jquery": ["node_modules/jquery/dist/jquery.min.js"]}, "rootDirs": ["src", "out"], / / put multiple directories under a virtual directory for use at runtime That is, the location of the imported files may change after compilation, and it is also set that virtual src and out can be in the same directory without changing the path and will not report an error "listEmittedFiles": true, / / printout file "listFiles": true// prints compiled files (including referenced declaration files)}}
3. Exclude
The function of the exclude property is to specify files or folders that the compiler needs to exclude.
Files under the node_modules folder are excluded by default.
{/ /... "exclude": ["src/lib" / / excluding files under the lib folder in the src directory will not be compiled]}
Like the include property, glob wildcards are supported:
* match 0 or more characters (excluding directory delimiters)
? Matches any character (excluding directory delimiters)
* / Recursively match any subdirectory
4. Extends
The function of the extends property is to introduce other configuration files and inherit the configuration.
All TypeScript files in the current directory and subdirectories are included by default.
{/ /... / extract the basic configuration into a tsconfig.base.json file, and then introduce "extends": ". / tsconfig.base.json"}
5. Files
The files attribute is used to specify a single list of files that need to be compiled.
All TypeScript files in the current directory and subdirectories are included by default.
{/ /... "files": [/ / specify that the compiled file is the leo.ts file "scr/leo.ts"]} in the src directory
6. Include
The function of the include attribute is to specify the files or directories that need to be compiled.
{/ /... "include": [/ / "scr" / / compiles all files in the src directory, including the subdirectory / / "scr/*" / / compiles only the files "scr/*/*" in the scr first-level directory / / compiles only the files in the scr secondary directory]}
7. References
The function of the references property is to specify project reference dependencies.
In project development, sometimes in order to facilitate the development of the front-end project and the back-end node project in the same directory, the two projects rely on the same configuration file and common file, but we want the front-end project to be flexibly packaged separately, so we can configure as follows:
{/ /... "references": [/ / specify the dependent project {"path": ". / common"}]}
8. TypeAcquisition
The function of the typeAcquisition attribute is to set the automatic import of library type definition files (.d.ts).
Contains 3 sub-attributes:
Enable: Boolean type. Whether to enable automatic import of library type definition files (.d.ts). Default is false.
Include: array type, which allows automatic introduction of library names, such as ["jquery", "lodash"]
Exculde: array type, excluded library name.
{/ /... "typeAcquisition": {"enable": false, "exclude": ["jquery"], "include": ["jest"]}}
VI. Examples of common configurations
In this part, we have found several configurations that are common in actual development. Of course, there are still many configurations that need to be explored by ourselves.
1. Remove comments from the code
Tsconfig.json:
{"compilerOptions": {"removeComments": true,}}
Before compilation:
/ / returns the current version number function getVersion (version:string = "1.0.0"): string {return version;} console.log (getVersion ("1.0.1"))
Compilation result:
Function getVersion (version) {if (version = void 0) {version = "1.0.0";} return version;} console.log (getVersion ("1.0.1"))
two。 Enable null and undefined detection
Tsconfig.json:
{"compilerOptions": {"strictNullChecks": true},}
Modify the contents of the index.ts file:
Const leo; leo = new Pingan ('leo','hello')
At this time, the editor will also prompt an error message. After executing tsc, the console reports an error:
Src/index.ts:9:11-error TS2304: Cannot find name 'Pingan'. 9 leo = new Pingan ('leo','hello'); Found 1 error.
3. Configuration reuse
Configuration reuse is achieved through the extends attribute, that is, one configuration file can inherit the configuration properties of another file.
For example, create a basic configuration file, configs/base.json:
{"compilerOptions": {"noImplicitAny": true, "strictNullChecks": true}}
The configuration of this file can be referenced in tsconfig.json:
{"extends": ". / configs/base", "files": ["main.ts", "supplemental.ts"]}
4. Generate the mapping code for enumerations
By default, enumerations do not generate mapping code after using the const modifier.
As we can see below, after using the const modifier, the compiler does not generate any mapping code for any RequestMethod enumerations, and when used elsewhere, inline the value of each member, saving a lot of money.
Const enum RequestMethod {Get, Post, Put, Delete} let methods = [RequestMethod.Get, RequestMethod.Post]
Compilation result:
"use strict"; let methods = [0 / * Get * /, 1 / * Post * /]
Of course, when we want to generate the mapping code, we can also set the configuration in tsconfig.json and set the preserveConstEnums compiler option to true:
{"compilerOptions": {"target": "es5", "preserveConstEnums": true}}
Finally, the compilation result is as follows:
"use strict"; var RequestMethod; (function (RequestMethod) {RequestMethod [RequestMethod ["Get"] = 0] = "Get"; RequestMethod [RequestMethod ["Post"] = 1] = "Post"; RequestMethod [RequestMethod ["Put"] = 2] = "Put"; RequestMethod [RequestMethod ["Delete"] = 3] = "Delete";}) (RequestMethod | (RequestMethod = {})) Let methods = [0 / * Get * /, 1 / * Post * /]
5. Turn off this type annotation hints
An error will be reported after compilation with the following code:
Const button = document.querySelector ("button"); button?.addEventListener ("click", handleClick); function handleClick (this) {console.log ("Clicked!"); this.removeEventListener ("click", handleClick);}
Error content:
Src/index.ts:10:22-error TS7006: Parameter 'this' implicitly has an' any' type. 10 function handleClick (this) {Found 1 error.
This is because this implicitly has an any type, and if no type annotation is specified, the compiler prompts "" this "implicitly has the type" any "because it has no type annotation." .
There are two solutions:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Specify the this type, such as the HTMLElement type in this code:
The HTMLElement interface represents all HTML elements. Some HTML elements implement the HTMLElement interface directly, while others indirectly implement the HTMLElement interface.
For more information about HTMLElement.
two。 Use the-- noImplicitThis configuration item:
A new compilation option is also added to TS2.0:-- noImplicitThis, which means that an error message is generated when the value of the this expression is of type any. When we set it to true, we can compile normally.
{"compilerOptions": {"noImplicitThis": true}}
7. Use examples in Webpack/React
1. Configure and compile ES6 code, JSX file
Create a test project, webpack-demo, with the following structure:
Webpack-demo/ |-package.json |-tsconfig.json |-webpack.config.js |-/ dist |-bundle.js |-index.html |-/ src |-index.js |-index.ts |-/ node_modules
Install TypeScript and ts-loader:
$npm install-save-dev typescript ts-loader
Configure tsconfig.json, support JSX, and compile TypeScript to ES5:
{"compilerOptions": {"outDir": ". / dist/", "noImplicitAny": true, + "module": "es6", + "target": "es5", + "jsx": "react", "allowJs": true}}
You also need to configure webpack.config.js so that it can handle TypeScript code, here you mainly add ts-loader to rules:
Const path = require ('path') Module.exports = {entry:'. / src/index.ts', module: {rules: [{test: /\ .tsx? $/, use: 'ts-loader', exclude: / node_modules/}]}, resolve: {extensions: [' .tsx', '.ts', '.js']} Output: {filename: 'bundle.js', path: path.resolve (_ _ dirname,' dist')}}
two。 Configure source map
To enable source map, we must configure TypeScript to output the inline source map to the compiled JavaScript file.
You only need to configure the sourceMap property in tsconfig.json:
{"compilerOptions": {"outDir": ". / dist/", "sourceMap": true, "noImplicitAny": true, "module": "commonjs", "target": "es5", "jsx": "react", "allowJs": true}
Then configure the webpack.config.js file to have webpack extract the source map and inline it into the final bundle:
Const path = require ('path') Module.exports = {entry:'. / src/index.ts', devtool: 'inline-source-map', module: {rules: [{test: /\ .tsx? $/, use:' ts-loader', exclude: / node_modules/}]}, resolve: {extensions: ['.tsx' '.ts', '.js']}, output: {filename: 'bundle.js', path: path.resolve (_ _ dirname,' dist')}} This is the end of "how to understand tsconfig.json". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.