I personally like TypeScirpt, write code with Ts to be more comfortable than Js too much, can greatly improve the efficiency of writing code, reduce the workload of code maintenance. Because I have the foundation of C++ and C#, I can get started with Ts quickly. Although there is no difficulty in using it, but for a long time, did not go to understand the compilation process and configuration of typescirpt, so they can not be considered to really understand it.
If you don’t know much about ts configuration and compilation process, then this article should help you.
The next part requires your environment to have TypeScript installed. Please make sure that TypeScript is installed, otherwise the tsc command will not be recognized.
I.tsc
Ts provides a command line function tsc, which can be used to compile Ts files into Js files.
First create a folder and index.ts file and go to the learnTsConfig folder.
You can enter some Ts code in the index.ts file, e.g.
Then use the tsc [ts file] command to compile the file.
|
|
As you can see, there is an index.js file generated in the same directory as src/index.ts, which is the compiled file, and the contents of the src/index.js file are as follows.
Specifying the ts file for the tsc command is not applicable to the project, we can’t add all the file paths to be compiled after the tsc command, so we usually use JSON configuration file (tsconfig.json) to configure the tsc compiler. When executing the tsc command, the tsc compiler will first look for the tsconfig.json file in the current directory. If there is no tsconfig.json file in the current directory, it will keep looking up the directory until it finds a tsconfig.json file, the directory where the tsconfig.json file is located is project’s root directory.
If you do not find a tsconfig.json file, the tsc command will not compile any files, but will only output the version number and help information.
The tsconfig.json file is described in detail below.
II. The tsconfig.json file
The tsconfig.json file supports JSON5 content, so you can add comments to the tsconfig.json file, using single quotes instead.
The structure of the tsconfig.json file is as follows.
In the following I will describe the configuration options divided into compiled options (configuration items under the compilerOptions field) and non-compiled options (root-level options outside the compilerOptions field).
First, under the learnTsConfig directory, create a new tsconfig.json file.
|
|
Non-compile options
Non-compiled options usually control information about the items (files) to be compiled by the typescript compiler, such as the ts files to be compiled.
-
filesfilesoption is used to indicate which files need to be compiled, you can add a set of file paths, support relative paths and absolute paths, relative paths are relative to the project root directory, that is, the directory where the tsconfig.json file is located, it is recommended that you use relative paths, avoid using absolute paths, so that even if the project changes the environment, you do not have to change the configuration.Create a new file
outerIndex.tsin the root directory, and the directory structure will be as followsEnter the following in the tsconfig.json file.
Execute the
tsccommand to compile, and the compiled file structure will be as follows. -
include&excludeIf there are few files in the project, using the
filesoption to set the target files to be compiled is a good choice, but when there are a lot of files or the project files are updated frequently, writing all the files to be compiled in thefilesarray is a bit tricky, and you have to update thefilesoption every time you add a ts file.So ts also provides
includeoption, which is similar tofiles, but you can use pattern match to delete the previously compiled js files and change the contents of thetsconfig.tsfile as follows.Execute
tsccompilation, the file structure is as follows, onlyindex.tsin thesrc/directory is compiled.excludedoes the opposite ofinclude, it is used to exclude certain files, it also supports pattern matching, clean up the js file and update thetsconfig.tsfile as follows.The
includeoption means that all ts files in the root directory are compiled, andexcludemeans that all ts files in thesrc/directory are excluded, so the compiled file structure oftscis as follows.By default typescript will automatically look for
.tsfiles and.d.tsfiles if you set theallowJScompile option (described later) to true, and will also look for.jsfiles if you set theallowJScompile option (described later) to true.src/**/*is equivalent tosrc/**/*.tsandsrc/**/*.d.ts(andsrc/**/*.jsifallowJsis true).There are some folders that typescript will automatically exclude, such as
node_modules,bower_components,jspm_packagesand<outDir>. If you want to force ts to compile ts files in these folders, you need to specify thefilesfile option.
Compiler Options
Compiler options are the relevant configuration under the compilerOptions field.
Output files
-
outDirBy default, ts compiled js files are in the same directory as the source files. Use the
outDiroption to specify the directory where the compiled files are located. Clean up the js files generated by previous compilation.Update the
tsconfig.jsonfile.Then execute the
tsccommand to compile, after compiling, thedist/folder will be generated, thedist/directory is the compiled js file, the structure of the directory is the same as the project directory structure. -
rootDirThe default root directory of typescirpt project is the directory where the
tsconfig.jsonfile is located, and all relative paths are relative to this root directory. We can change the project’s root directory location with therootDiroption. Delete the dist folder and update thetsconfig.jsonfile.Execute the tsc command and the compiled directory will be as follows.
In most cases, we just keep the default behavior of TypeScript and use the
tsconfig.jsonfile located in the root of the project. -
removeCommentsThe
removeCommentsoption is used to remove commented code from the compiled js file.First clean up the project and update the
tsconfig.jsonfile as follows.Update the contents of the
src/index.tsfile.tscis compiled, and the compileddist/src/index.jsfile reads as follows.You can see that the comments have not been removed. Update the
tsconfig.jsonfile.Compile again, and the compiled
dist/src/index.jsfile is as follows.You can see that the comment content has been removed.
-
moduleSuppose you are developing a project that needs to run in a nodejs environment, and in the project you use
importto introduce modules, butnodejsdoes not support it. nodejs uses the CommonJS module system. To convert the compiled js fileimportstatements torequirestatements, you can configure"module": "CommonJS".Here, let’s try it manually. Update the
tsconfig.jsfile.Add the add.ts file to the src directory with the following content.
Update the
src/index.tsfile.Compile the file, look at
dist/src/index.jscontent as follows, you can see that theimportstatement has been converted to arequirestatement. -
outFileoutFilecan specify that the compiled result file is packaged as a bundle, i.e. a js file, provided that themoduleoption is set toSystemorAMD. If you want to support other module options, you can use tools like webpack, parcel, etc.For a simple experiment, update the
tsconfig.jsonfile as follows.Only the
dist/bundle.jsfile is generated after compilation.
source map
-
sourceMapThe source-map file represents a mapping relationship between the compiled source file and the output result file, which plays a very important role in debugging the project and allows us to display the source code in the browser developer tools for debugging. If the debugger looks at the compiled code, then debugging is such a painful thing.
The source-map file is automatically generated by the compiler tool and ends with the
.mapsuffix, it is a JSON file with the following structure.The
filefield indicates the name of the output file corresponding to the source-map file, and thesourcesfield indicates the compiled source file. Themappingattribute is a base64 encoded value that represents the relationship between the source file and the output file.And the compiled output file will have a comment at the end of the
sourceMappingURLfield, indicating the map file location, and this comment will be read by the browser to locate the map file.To generate the source-map file, you can set the
sourceMapfield to true.Update the
tsconfig.jsonfile.Execute the
tsccommand, which will generatedist/bundle.jsanddist/bundle.js.mapafter compilation. -
inlineSourceMapThe
sourceMapoption generates a separate.mapfile for the compiled js file. By settinginlineSourceMapto true, you can avoid generating.mapfiles and inline the map directly into the compiled js file.Update the
tsconfig.jsonfile.After compiling, view the compiled
dist/bundle.jsfile.You can see that the
sourceMappingURLis directly followed by the base64 data (map file content).
type declaration
The most important role of typescript is to make js support types and turn it into a strongly typed language.
-
declarationSet the
declarationfield to true to automatically generate declaration files.Update the
tsconfig.jsonfile.Executing the tsc command to compile, you can see the
dist/**/*.d.tsfile generated, which is the declaration file for the corresponding*.jsfile. With these declaration files, the ts compiler can know the API structure of the package, even if the compiled JavaScript file does not contain any type information.The directory of the generated dist files is as follows.
-
declarationDirWhen
declarationis set toture, the ts compiler puts the corresponding .d.ts file into the same level as the compiled js file. You can put all declaration files in the same directory by settingdeclarationDir.Update the
tsconfig.jsonfile as follows.Execute the tsc command, you can see the
dist/types/directory is generated, the structure of the directory is the same as the source file directory, except that they are all.d.tsdeclaration files. -
libtypescirpt has some built-in TypeScirpt declaration files, such as
Promise,Object.freezeand the declaration of the browser API. These declaration files can provide code hints and warnings. They are usually stored in thelibfolder, which we call the standard library. You can manually select which libraries to import by setting thelibfield. -
typeRootsWhen you publish your typescript program, as an npm package, you may publish the compiled JavaScript package, so that non-typescript programs can introduce the npm package, in order to provide declaration information, you can also provide the corresponding declaration file, so that typescript compilers and IDEs (such as vscode) can provide type hints, error hints based on the declaration file. To generate the declaration file, you just need to set
declarationtotrue.But not all programs are written in typescript, for example lodash, which itself is written in javascript, so it can’t use the function provided by ts to generate the declaration file automatically. So you need to manually provide declaration files for npm packages that don’t have them.
The DefinitelyTyped community’s job is to provide declaration files for the more popular npm packages that don’t have them. You can provide a declaration file for an npm package by installing a declaration file package that starts with
@types.For example
npm install @types/lodash,@types/lodashis the declaration file for thelodashpackage.By default, typescript imports all type declarations from the
node_modules/@typesfolder into the global space, but note that only declarations in the script file will be imported into the global space, the module file is hidden from the global space.type-root is the directory where the package declaration files are stored, and can be set to a series of file paths via the
typeRootsoption, indicating where typescript imports type information from, the default value isnode_modules/@types.By setting
"typeRoots": [". /my-types"], typescript will only import declarations from themy-typesfolder, not from thenode_modulesfolder. -
typestypeRootsis used to import all declarations in the directory into the global space, but iftypesis set, only the package declarations specified bytypeswill be imported into the global space.
JavaScript compilation
By default, typescript is compiled without the js file. This default behavior can be changed with allowJS and checkJS.
-
allowJSWhen you introduce a module in a typescript file with an
importstatement, such asimport {add} from ". /add, by default the ts compiler will automatically look forsrc/add.tsandsrc/add.d.tsand it will not considersrc/add.js, we can change this default behavior by settingallowJStotrue.First, update the
tsconfig.jsonfile as follows.Create a new
src/add.jsand enter the following code.Introduce the
addfunction insrc/index.js.By default,
allowJSisfalse, so the compiledadd.jsfile will not be included in thedist/src/directory after the tsc compilation.Update the
tsconfig.jsonfile to setallowJSto true.Recompile, and after compiling,
add.d.tsandadd.jsfiles will be added to thedist/src/directory.So, if you want your project to support js files, just set
"allowJs": true. -
checkJsUsing
allowJSallows the compiler to include js files in the compilation stage, but the compiler does not type check the js files. Type checking is an important feature of ts that greatly improves our development efficiency, so in order to allow the ts compiler to type check js files, you need to set"checkJS": true.To explain further, first add
const num = parseInt(1.5);to the top ofadd.js.Then compile it with tsc and it compiles successfully.
Then update the
tsconfig.jsonfile.Compile with tsc again and the compilation should report an error.
Because
checkJSis true at this point, the ts compiler will type check the js file, and theparseIntfunction accepts a string as an argument, but1.5is of typenumber, so the type is not compatible, so the compilation fails. If you are using vscode editor withcheckJSenabled, the editor should give you a smart error when you hit the codeconst num = parseInt(1.5);.
III. Summary
There are many configuration fields in tsconfig, this article aims to introduce its basic usage and basic structure, and does not cover all of them. I hope that through this article, you can understand tsc compiler, know how to configure tsc compiler and understand its principles.
For more tsconfig configuration, please refer to TSConfig Reference.