Typescript - 安装与配置
TS 简介
官网说 ts 是 js 的超集,就是说 ts 涵盖了 js,它的内容比 js 要多,它编译出来的结果还是 js, 那为什么要用它呢,主要还是因为我们的 js 是一门弱类型的语言,什么意思呢,我来举个很简单的例子:
可以看到编辑器中程序没有报错,但是控制台执行了之后,有变量没有定义的error,这个就是编译的时候没有检测出error,在执行的时候出现了错误,所以我们应该尽量在编译的时候就把这些错误给检测出来,然后解决这些问题,这样才能保证在运行的时候代码不出错。那 ts 就是来帮助你的。
TS 安装
通过 npm, 全局安装typescript。 执行下面的命令。
npm install -g typescript
安装完成之后再执行命令
tsc -h
就能看到 Typescript 的 帮助命令, 我这个版本的如下
我们需要关注的就三个,一个是tsc --init, 这个会初始化一个默认的tsconfig.json,后面都根据这里面的配置来编译ts文件,一个是 tsc xxx.ts, 这个命令就是把这个 ts 文件编译成对应的 js 文件,还有一个就是 tsc -p ./xxxx/tsconfig.json 这个是使用这个ts配置文件来编译整个项目。
项目创建
我们来创建一个ts项目, 首先新建一个文件夹ts-project,然后在该目录下执行命令
npm init
一直回车,项目就有了,在ts-project 目录下新建一个 src 目录, 我们来写一个index.ts 文件, 内容如下
const coolName = "cool";
console.log("coolName", coolName);
如果我们把第一行注释了,下面一行就会直接报错,和我们在js里面不一样
我们把代码再改回去,然后在 ts-project 目录下, 执行命令
tsc --init
目录结构如下
会生成一个tsconfig.json 文件,那我们来研究下这个配置文件。
tsconfig.json文件详解
默认生成的这个 tsconfig.json,里面的对象只有一个属性就是"compilerOptions",而且里面很多属性选项都注释了,每个属性后面都有对应的解释,说明这个配置项是用来干什么的,我们具体的来看下,挑一些实用的来说一下。
{"compilerOptions": {"target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,"module": "commonjs" /* Specify what module code is generated. */,"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,"strict": true /* Enable all strict type-checking options. */,"skipLibCheck": true /* Skip type checking all .d.ts files. */}
}
这个是初始化之后生成的,其他的注释的我都删了,接下来就添加一些我们需要的配置。
1 outDir
{"compilerOptions": {"outDir": "./dist/out" /* Specify an output folder for all emitted files. */,"target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,"module": "commonjs" /* Specify what module code is generated. */,"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,"strict": true /* Enable all strict type-checking options. */,"skipLibCheck": true /* Skip type checking all .d.ts files. */}
}
添加outDir属性, 并设置其值, 顾名思义,这个就是编译之后的文件的文件目录,没有该目录则会自动创建,下面我们在根目录执行命令
tsc -p ./tsconfig.json
就会把之前我们写的 index.ts 文件编译成index.js, 并放到该目录下。
2 target
设置编译之后的 js 版本,现在默认给的 es2016,我们看看编译好的 index.js 内容
这里还是能看到 const 关键字来修饰变量, 因为es2016 也是属于 es6 规范,这里我们修改下target的值为 es5
{"compilerOptions": {"outDir": "./dist/out" /* Specify an output folder for all emitted files. */,"target": "es5" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,"module": "commonjs" /* Specify what module code is generated. */,"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,"strict": true /* Enable all strict type-checking options. */,"skipLibCheck": true /* Skip type checking all .d.ts files. */}
}
再来编译一下,发现 index.js 如下
const 变成了 var, 这是 es5 的规范,所以这个target 可以定义我们编译好的 js 规范版本, 常用的就是es5, es2015, es2016, 当然 es2015 也是属于 es6 规范哟。
3 lib
引用库文件,就是ts的声明文件,如果没有引用的话,对应的函数或对象都是使用不了的。这个和 target 设置有关,举个例子,我们将target 设置为 es5, 然后不设置lib,我们在index.ts 编写 ES6 的代码,如promise, 编辑器就会报错:
{"compilerOptions": {"outDir": "./dist/out" /* Specify an output folder for all emitted files. */,"target": "es5" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,"module": "commonjs" /* Specify what module code is generated. */,"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,"strict": true /* Enable all strict type-checking options. */,"skipLibCheck": true /* Skip type checking all .d.ts files. */}
}
所以我们需要配置lib, 让我们可以使用es6 的特性
{"compilerOptions": {"outDir": "./dist/out" /* Specify an output folder for all emitted files. */,"target": "es5" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,"lib": ["DOM", "ES2015"],"module": "commonjs" /* Specify what module code is generated. */,"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,"strict": true /* Enable all strict type-checking options. */,"skipLibCheck": true /* Skip type checking all .d.ts files. */}
}
当然如果我们的target 是 es6, 那我们就不需要配置这个lib了,是可以直接使用es的新特性的
{"compilerOptions": {"outDir": "./dist/out" /* Specify an output folder for all emitted files. */,"target": "es6" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,"module": "commonjs" /* Specify what module code is generated. */,"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,"strict": true /* Enable all strict type-checking options. */,"skipLibCheck": true /* Skip type checking all .d.ts files. */}
}
这里是没有报错。还有一点需要注意的是,这里的lib如果不配置的话是有默认配置的,如果你配置了,就会覆盖默认的配置,所以你需要把所有的配置补全,比如dom, 如果你的代码运行环境不在浏览器,那可以配置,如果在浏览器, 别忘了还有一个dom需要配置上,最终附上我们的配置
{"compilerOptions": {"outDir": "./dist/out" /* Specify an output folder for all emitted files. */,"target": "es5" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,"lib": ["DOM", "ES6"],"module": "commonjs" /* Specify what module code is generated. */,"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,"strict": true /* Enable all strict type-checking options. */,"skipLibCheck": true /* Skip type checking all .d.ts files. */}
}
4 allowJs checkJs
这两个配置是连在一起使用的,默认都是false, 我们现在改成true, 当然了,ts 的项目,基本都是 ts 文件, 所以这两个配置不常用。
{"compilerOptions": {"outDir": "./dist/out" /* Specify an output folder for all emitted files. */,"target": "es5" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,"lib": ["DOM", "ES6"],"allowJs": true,"checkJs": true,"module": "commonjs" /* Specify what module code is generated. */,"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,"strict": true /* Enable all strict type-checking options. */,"skipLibCheck": true /* Skip type checking all .d.ts files. */}
}
然后在src 目录下新建一个hello.js, 并编写代码
console.log("hello js", intro);
然后就发现了错误提示
我们不管这个错误,直接执行编译命令,在控制台也会输出这个错误
这个就是checkJs 属性为true, 帮助你检查js的error, 我们修改一下这个文件, 定义一下这个变量,再执行编译命令
能看到输入目录里面有hello.js 这个文件, 这个就是allowJs属性为true的作用, 允许我们编译js文件。
5 strict
开启严格检查,这个开启了的话会影响到很多的配置,我们初始化的时候,这个给出的是true, 我们先给它false, 再来看其他的与之相关联的配置
- noImplicitAny 没有明确的数据类型会报错
{"compilerOptions": {"outDir": "./dist/out" /* Specify an output folder for all emitted files. */,"target": "es5" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,"lib": ["DOM", "ES6"],"allowJs": true,"checkJs": true,"strict": false /* Enable all strict type-checking options. */,"noImplicitAny": true,"module": "commonjs" /* Specify what module code is generated. */,"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,"skipLibCheck": true /* Skip type checking all .d.ts files. */}
}
再修改下index.ts 代码,定义了一个sum 箭头函数,但是由于两个输入参数a, b没有明确的数据类型,所以编辑器给出了报错
- strictNullChecks 设置为null 和 undefined 会报错
{"compilerOptions": {"outDir": "./dist/out" /* Specify an output folder for all emitted files. */,"target": "es5" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,"lib": ["DOM", "ES6"],"allowJs": true,"checkJs": true,"strict": false /* Enable all strict type-checking options. */,"noImplicitAny": true,"strictNullChecks": false,"module": "commonjs" /* Specify what module code is generated. */,"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,"skipLibCheck": true /* Skip type checking all .d.ts files. */}
}
这里我们先设置strictNullChecks为false, 我们可以看到在代码里面可以将一个string类型的变量赋值为null 或者 undefined 都是合法的,编辑器没有报错
现在我们将strictNullChecks为true,可以看到编辑器已经给出了提示
- strictFunctionTypes 设置意义不大,官方解释是设置函数参数是否遵循双向协变检查(啥呀这是),举个例子吧,先设置这个属性值为false, 修改 index.ts 代码
interface Person {age: number;
}
interface Man extends Person {sex: string;
}
let getIntro = (person: Person) => {console.log(person.age);
};
let getIntro1 = (man: Man) => {console.log(man.age);
};
getIntro = getIntro1
发现代码没有报错,可以将函数getIntro1 赋值给 getIntro,这是因为Man 继承 Person, 由man里面的属性肯定包含了Person的属性,所以这个代码没有逻辑上的错误,开启了这个检查后,就必须要求参数的类型一致,不然的话就会报错, 当然我们平时应该也不会这样写代码,所以这个属性意义不大。
- strictBindCallApply
这个用的也不是很多,设为 true 后对 bind、call 和 apply 绑定的方法的参数的检测是严格检测,但是我们在es6 里面谁还去用bind call apply呢,所以大概知道是什么意思就行了。 - strictPropertyInitialization 检查类的非undefined的属性是不是在构造函数里面初始化了
{"compilerOptions": {"outDir": "./dist/out" /* Specify an output folder for all emitted files. */,"target": "es5" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,"lib": ["DOM", "ES6"],"allowJs": true,"checkJs": true,"strict": false /* Enable all strict type-checking options. */,"noImplicitAny": true,"strictNullChecks": true,"strictFunctionTypes": true,"strictPropertyInitialization": true,"module": "commonjs" /* Specify what module code is generated. */,"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,"skipLibCheck": true /* Skip type checking all .d.ts files. */}
}
- noImplicitThis 设为true的时候,不允许this 的类型为any
- alwaysStrict 编译好的js文件为严格模式, 头部有 "use strict " 字样。
- noUnusedLocals
检查有无未使用的变量,理解起来很简单,就不举例说明了 - noUnusedParameters
检查函数参数中是否有未使用的参数 - noImplicitReturns
检查函数是否有返回值 - noFallthroughCasesInSwitch
检查switch语句中是否有case 没有使用break;
这些配置都可以用一个配置开启,那就是属性strict, 设置为true后, 这些属性都自动开启。
6 baseUrl and path
这个是解决模块之间引用路径的问题,举个例子,我们在src 目录下再建几个目录如下,
pages/index.ts 文件如下
utils/index.ts 文件如下
可以看到pages/index.ts 里面引入utils/index.ts文件的时候用了 “…/…/” 这种路径,如果引入的很多,代码看起来就不是很简洁,我们现在来修改下tsconfig.json
{"compilerOptions": {"outDir": "./dist/out" /* Specify an output folder for all emitted files. */,"target": "es5" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,"lib": ["DOM", "ES6"],"allowJs": true,"checkJs": true,"strict": false /* Enable all strict type-checking options. */,"noImplicitAny": true,"strictNullChecks": true,"strictFunctionTypes": true,"strictPropertyInitialization": true,"noImplicitThis": true,"alwaysStrict": true,"baseUrl": "src","paths": {"@utils/*": ["./utils/*"]},"module": "commonjs" /* Specify what module code is generated. */,"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,"skipLibCheck": true /* Skip type checking all .d.ts files. */}
}
这样引入的时候就可以这样写
比之前的是不是好很多。
总结
还有一些其他的配置,我没有再罗列出来了,其实这些东西我们都可以自己去尝试下,刚开始写TS的时候也许很痛苦,就像eslint, 当你开启之后,你的代码的健壮性会大大提高,出bug的几率也会大大降低,会培养自己良好的编程习惯,看看现在各个热门的 js 框架都推出了 ts 版本,由此可见一斑, 学好 ts 还是很有必要的。
Typescript - 安装与配置相关推荐
- 安装scss_React Native + Typescript + Scss开发配置过程
React Native + Typescript + Scss开发配置过程 开发工具 Visual Studio Code React Native Tools扩展 Typescript支持 入口文 ...
- g4e基础篇#3 Git安装与配置
现在你已经对Git有了最基本的了解,现在让我们开始动手开始安装和配置Git环境. Git工具包括Git命令行工具,图形化工具和服务器环境:在我们这个教程中,我们会使用以下软件配置我们的环境: • Wi ...
- TypeScript 安装与使用
TypeScript 安装与使用 本节介绍 TypeScript 的安装与两种使用方式,大家根据本节所介绍的流程一步步操作,相信很快就能编写自己的 TypeScript 代码. 1. 慕课解释 环境准 ...
- ionic3 教程(一)安装和配置 1
链接: ionic3教程(一)安装和配置 ionic3教程(二)登录页制作 ionic3教程(三)设置页制作 ionic3教程(四)安卓硬件返回键处理 ionic3 教程(五)基本的网络请求 学习本教 ...
- Maven安装与配置(最实用!!!)eclipse中配置maven
Maven安装与配置 一.需要准备的东西 JDK Eclipse(本章主要是在eclipse中进行配置maven) Maven程序包 二.下载与安装 1. 前往maven下载最新版的Maven程序: ...
- Portainer 安装与配置
文章目录 Portainer 安装与配置 一.介绍 二.安装使用 1.单机运行 2.基于swarm集群方式运行 Portainer 安装与配置 一.介绍 Portainer 是一个开源.轻量级Do ...
- Myeclipse安装、配置、测试
Myeclipse安装.配置.测试(win7_64bit) 目录 1.概述 2.本文用到的工具 3.安装与激活 4.JavaSE开发测试(确保JDK已正确安装) 5.JavaEE开发测试(确保服务器和 ...
- [网摘学习]在Ubuntu上安装和配置OpenStack Nova之二
再收藏一份Openstack的文章,这两天的操作与此相同.但其中出现的问题还需要查找原因.待个人继续学习研究. 原文参考:http://www.linuxde.net/2011/11/1599.htm ...
- centos6.5 php5.2,Linux中PHP安装与配置(CentOS-6.5:php-5.2.13)
1 PHP简介 PHP(PHP: Hypertext Preprocessor的缩写,中文名:"超文本预处理器")是一种通用开源脚本语言.语法吸收了C语言.Java和Per ...
最新文章
- 添加触发器后自增ID会变
- 机器学习基础(1)——绪论
- 免费!200块全志XR806开源鸿蒙开发板试用
- 为什么要进入 5G 时代?
- 使用TopShelf做windows服务安装 ---安装参数解释
- 投资 2 -- 新股民必须树立正确的价值观
- Blast中文手册(5)
- ubuntu16.04下设置静态IP
- Nginx官方文档(十一)【HTTP之ngx_http_core_module】
- (一)1. 数据流图(DFD)概念及画法
- new和malloc区别
- excel函数去重_Excel 2010中去除重复项的几种常用技巧
- php realpath 缓存,PHP的Realpath Cache
- DSP28335 SPWM之斩波器PWM-Chopper (PC)与Trip-Zone (TZ)
- android手机查看u盘中图片吗,安卓手机当U盘使用的图文教程
- 出现This dependency was not found:解决方法,亲测有用
- 2022年12月最新python学习基础教程01
- python字符串最后一次的索引_lastIndexOf方法——获取字符最后的索引
- 多任务---进程、进程池
- 互动电影游戏-H5互动游戏方桉之品牌营销
热门文章
- 抗击肺炎,我们能做到的,就是别让爱隔离——python分析B站三个视频弹幕内容,云图数据。
- 使用wait函数获取子进程终止状态
- Windows 10企业批量部署实战之WDS配置
- 二本学历,3年软件测试点点点,25K入职阿里巴巴
- 《Linux C编程环境》 课程大实验 及近期练习题:计算器,复写机,目录树创建,批处理执行器,扫雷
- MMORPG传奇类手游《空空西游》完整源码(客户端cocos2d-js+服务端pomelo+cocosStudio工程+搭建教程)
- Ansiable批量管理工具
- Win10无法开机提示自动修复无法修复你的电脑的有效解决方法
- latex学习笔记——latex的字体字号设置
- python坦克大战