TypeScript engineering practice plan

The previous article systematically summarized and learned the basic common syntax of TypeScript. But our purpose of learning TypeScript is not to build a "small hut", but to build "tall buildings", which is exactly the advantage brought by TypeScript's type system. This blog will learn some knowledge points of TypeScript engineering . The specific content includes: tsc compilation options, tsconfig.json configuration, and webpack packaging ts code.

1.TypeScript—compilation options and tsconfig.json configuration options

JavaScript code can be executed directly by the browser, while TypeScript needs to be compiled before it can be executed, such as using tsccommand compilation. But this will be very troublesome, every time you have to run the command, it can only be executed after compilation. And there is more than one TypeScript file written in the project. If there are multiple ts files, it would be too troublesome for us to compile them one by one. So let's learn TypeScript's compilation options and tsconfig.json configuration options.

Through compilation options, we can write TypeScript more elegantly, and many things that need to be done manually can be done automatically. We can also configure ts through compilation options. For example, if the ts code I wrote has a syntax problem, it will not be compiled. Another example is that I hope that my code compiled into ES6 version can be configured.

TypeScript provides a lot of compilation options with different functions. You can directly compile the .ts file by following the parameter with the tsc command , or you can compile it by configuring the properties in the tsconfig.json file. compilerOptionsBut beware : the tsconfig.json file is ignored when an input file is specified on the command line.

We will learn in detail through code and cases below, first create a directory study, and then create a main.ts file in the current directory.

Let’s try this option briefly first --watch. Let’s write some code in main.ts:

enum Season {
    
    
  Spring,
  Summer,
  Autumn,
  Winter
}

Execute on the command line:

tsc main.ts --watch

After we run this command, the ts compiler will start to automatically monitor the file changes.
insert image description here
When we change the content of the main.ts file, for example, we add a new line of code:

enum Season {
    
    
  Spring,
  Summer,
  Autumn,
  Winter
}

let x:number=1

The command line will display that the file has changed, and compile it automatically.
insert image description here
The compile option --watchcauses the compiler to run in watch mode, which watches the output files and recompiles when they change. The advantage of this is that we don't have to manually compile the main.ts file in the future.

However, there is another problem here, if I still have a ts file, for example, I create another index.ts. We also want to monitor the changes of this file, so we have to open another command line to run the monitoring command. If you want to monitor multiple files, this method is actually not elegant enough, and it is not suitable for our daily development. We want to compile all the ts files in the directory into js files by running only one command.

Very simple, we need to execute the following command in the current directory first:

tsc --init

--initThis option initializes the TypeScript project and generates a tsconfig.json configuration file. We will find that the content inside is very messy, we can delete all the content inside the braces, leaving only one brace.

Then, we can monitor all ts files by running the following command:

tsc --watch 或 tsc -w

OK, here, I finally lead to the tsconfig.json file. This file is really different from ordinary json files. Ordinary json files cannot write comments in it, but in this tsconfig.json file, we can write js comments arbitrarily in it.

{
    
    
//可以写注释

/*
 可以写注释哦
*/

}

tsconfig.json is the configuration file of the ts compiler. If there is a tsconfig.json file in a directory, it means that this directory is the root directory of the TypeScript project. The ts compiler can compile the code according to the information in this configuration file. Many configurations can be written in this configuration file, and the next thing we will study is its configuration options .

Main configuration items of tsconfig.json
A tsconfig.json file mainly has the following configuration items:

{
    
    
  "compilerOptions": {
    
    },
  "files": [],
  "include": [],
  "exclude": [],
  "extends": "",
  "compileOnSave": false,
  "typeAcquisition": {
    
    }
}

compilerOptions configuration item
The following is a summary of commonly used compilerOptions attribute configuration:

{
    
    
  "compilerOptions": {
    
    
    "target": "ESNext", /* 指定编译之后的版本目标: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT' (最新版本的ES) */
    "module": "ESNext", /* 指定要使用的模块标准: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    "noImplicitAny": false, /* 是否默认禁用 any */
    "declaration": true, /* 是否自动创建类型声明文件 */
    "strict": true, /* 启动所有类型检查 */
    "jsx": "preserve", /* 指定jsx代码用于的开发环境 */
    "importHelpers": true, /* 引入tslib里的辅助工具函数*/
    "moduleResolution": "node", /* 选择模块解析策略,有'node'和'classic'两种类型 */
    "experimentalDecorators": true, /* 启用实验性的装饰器特性 */
    "esModuleInterop": true,  /* 通过为导入内容创建命名空间,实现CommonJS和ES模块之间的互操作性 */
    "allowSyntheticDefaultImports": true, /* 允许从没有默认导出的模块中默认导入 */
    "allowSyntheticDefaultImports": true,/*允许对不包含默认导出的模块使用默认导入。这个选项不会影响生成的代码,只会影响类型检查。*/
    "sourceMap": true, /* 是否生成map文件 */
    "baseUrl": ".", /* 工作根目录 */
    "types": [], /* 指定引入的类型声明文件,默认是自动引入所有声明文件,一旦指定该选项,则会禁用自动引入,改为只引入指定的类型声明文件,如果指定空数组[]则不引用任何文件 */
    "paths": {
    
     /* 指定模块的路径,和 baseUrl有关联,和 webpack 中 resolve.alias 配置一样 */
      "@/*": [
        "src/*"
      ]
    },
    "lib": [ /* 译过程中需要引入的库文件的列表,不设置也行 */
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ],
    "outDir": "./dist", /* 用于指定编译后文件所在的目录 */
    "outFile": "./dist/app.js", /* 将我们的代码合并编译成一个文件(仅在module为amd或system时适用) */
    "allowJs": true, /*允许编译 js 文件,默认为false。设置为 true 时,js 文件会被 tsc 编译,否则不会。一般在项目中 js, ts 混合开发时需要设置。*/
    "checkJs": true, /*是否检查js的代码符合语法规范,默认为false*/
    "removeComments": true, /*是否移除注释,默认为false*/
    "noEmitOnError": true, /*当有错误时不生成编译后的文件,默认为false*/
    "alwaysStrict": true, /*是否为编译后的js开启严格模式,默认为false*/
  }
}

files, include, exclude, and extends options

files is an array list, write the relative or absolute path of the files to be compiled, glob matching mode is not supported.

include is an array list, write the path of the file to be compiled, and supports glob matching mode.

exclude is also an array list, written to exclude certain file paths, these files are excluded from the list to be compiled, and glob matching mode is supported.

The glob wildcards are:
* matches file path characters (excluding directory separators)
? matches any character (excluding directory separators)
**/ recursively matches any subdirectory
If neither "files" nor "include" is specified, compile By default, the compiler includes all TypeScript files (.ts, .d.ts and .tsx) in the current directory and subdirectories, excluding files specified in "exclude".

If the allowJs option is enabled, the .js and .jsx files are also included by the compiler.

Examples are as follows:

{
    
    
  "files": [
  "core.ts",
  "index.ts",
  "types.ts"
  ],
  "exclude": [
    "node_modules", 
    "lib", 
    "**/*.test.ts"
  ],
  "include": [
    "src/**/*"
  ],
}

"exclude" will by default exclude node_modules, bower_components, jspm_packages and directories if not specified otherwise.

Any files referenced by files specified by "files" or "include" are also included.

Priority: command line configuration > files > exclude > include

extends: String type, pointing to the path of another file to be inherited. For example:

{
    
    
  "extends": "config/base.json"
}

The meaning of this configuration item is that we can use the "extends" attribute to import the configuration options in the configuration file whose path is "config/base.json".

2. Use webpack to package ts code

In actual development, it is very rare to directly use the ts compiler to compile code, because we usually use ts in combination with packaging tools when we develop some large-scale projects, and we use webpack more often. Let's learn to summarize the integration of ts and webpack, and use webpack to package ts code.

We first create a directory study, and then run the following command to generate the package.json file:

npm init -y

After running the command, a package.json file will be generated under the current command
insert image description here
and then run the following command to install development dependencies such as webpack and webpack-cli command line tools:

npm i -D webpack webpack-cli typescript ts-loader

insert image description here
Next, we need to manually create a webpack.config.js configuration file in the root directory, create a src directory under the root directory, and create an index.ts file in the src directory:

webpack.config.js code:

//引入一个Nodejs包,用于处理路径
const path=require('path')

//webpack中所有的配置信息都应该写在module.exports中
module.exports={
    
    
    //指定入口文件
    entry: "./src/index.ts",
    //指定打包文件所在的目录
    output: {
    
    
        //指定打包后的目录
        path: path.resolve(__dirname,'dist'),
        //打包后文件的文件名
        filename: "bundle.js"
    },
    //指定webpack打包时要使用的模块
    module: {
    
    
        //指定要加载的规则
        rules: [{
    
    
            //指定规则对哪些文件生效,正则表达式
            //匹配所有以ts结尾的文件
            test: /\.ts$/,
            //用ts-loader处理
            use: 'ts-loader',
            //要排除的文件
            exclude: /node-modules/
        }]
    },
    //打包模式,是生产模式production还是开发模式development
    mode: "development"
}

Then, we create a tsconfig.json file in the root directory and write the following configuration:

{
    
    
  "compilerOptions": {
    
    
    "module": "ES2015",
    "target": "ES2015",
    "strict": true
  }
}

We use webpack to package, and add the following configuration to the script configuration node in package.json:

  "scripts": {
    
    
    "build": "webpack"
  }

At this point, we can npm run buildpackage the project through commands. Of course, there are many things worth configuring in webpack, so I won’t write them one by one here. And if it's front-end development, different front-end frameworks have corresponding scaffolding that can be used, so it doesn't have to be so troublesome.


Forecast: The next blog will use TypeScript to develop a Snake game for proficiency in TypeScript. Interested friends must not miss it!


Guess you like

Origin blog.csdn.net/weixin_50216991/article/details/127122963