OveUI博客
老前端的戎码生涯

typescript学习之路(一) —— 简介以及准备工作

前言
为什么ts会叫typescript呢?type类型的意思,script就是javascript,合起来就是类型js,简单来说就是对js进行一种类型规范。学过js的都知道js是Brendan Eich大佬花了21天就撸好的,虽然后来js也被修改过,但总归逃不了js是个弱类型语言的事实。

比如我们定义一些常见的js变量:

var num = 10; // 数字类型
var str = 'ts'; // 字符串类型
var boo = true; // 布尔类型
var obj = {}; // 对象类型

还有数组对象,date对象等等,不难发现,我们可以通过var+关键字定义几乎所有变量,这在java和c++等语言中是不可想象的,因此很多后端朋友转到前端时总觉得怪异,这还不是很怪异的,更怪异的是es5定义对象也就是类的实现。而巨无霸微软为了解决这个问题,也为了能让js更适合大型多人合作项目,由此开发了ts,ts其实是js的一个超集,主要是对js提供了一个类型支持,正如名字那样,typescript。

学习ts的好处。类型系统使得团队合作开发更规范,编译时就能发现大多数低级错误。为项目以后的维护提供便利。当然ts也对es6提供了更好的支持,现如今ts社区蓬勃发展,so,赶紧学ts吧。

学ts之前,你首先得具备基本的js功底,还要有一定的es6功底,js推荐《JavaScript 高级程序设计》,而es6则推荐阮一峰大神的《es6入门》

准备工作
安装TypeScript
TypeScript 的命令行工具安装方法如下:

npm install -g typescript // 全局安装

当然大家也可以使用cdn,如bootCdn、jsdeliver。

运行TypeScript
安装完成之后新建文件index.ts主要这里是.ts,而不是.js啦,然后我们输入以下代码

console.log('hello ts')

然后我们在这个文件目录下执行tsc index.ts,然后我们就可以看到在index.ts的同级出现了一个index.js的文件,这就是ts编译后的js文件了,我们直接在index.js目录下执行node index.js,就可以在终端看到我们的hello ts输出,当然我们也可以新建一个index.html,在里面引入我们的js,打开控制台也可以看到这hello ts。这里我们的第一个ts文件就搞定了。

当然为了节约时间,我们不可能每次编译完,都运行下tsc命令,来重新生成一个新js文件出来,这里向大家介绍一个监听ts的方法,让系统给我们更新。首先我们在刚在的文件目录下执行命令tsc –init,这个时候会生成一个tsconfig.json的配置文件,它长这样

{
"compilerOptions": {
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */

/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */

/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */

/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */

/* Advanced Options */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}

我们不需要动这个默认配置,之后我们只需要执行tsc index.ts -w监听ts文件就可以啦,这个命令可以一直监听我们的ts文件,当文件修改时,会自动编译成新的js文件并输出到配置文件同目录下。我们可以node执行js文件在终端查看,当然也可以在index.html中引入查看,我个人比较懒,用的是终端,而且用的hotnode来进行对js文件的监听,这样输入完ts,编译完成之后,终端也会实时显示。

npm install -g hotnode // 全局安装node热更新依赖

安装完,执行hotnode index.js即可

当然,为了能够知道知道我们的语法错误,我们还可以安装tslint来对ts文件的语法进行检测,这个就相当于eslint对于js的检测一样。

npm install -g tslint// 全局安装tslingt

同样在编辑器内部插件市场里也可以安装,这样我们的一些简单错误,插件就可以帮我们自动完成修复

赞(0)
未经允许不得转载:UI树欲静 » typescript学习之路(一) —— 简介以及准备工作