第一章、欢迎来到TypeScript的世界
一、环境配置
TypeScript(本系列文章将全部简称为TS)的爹是谁,不是我们要讨论的话题,有兴趣的网友自己去Baidu。直接进入正题,TS它是javascript的一个超集,意思就是对javascript做了更多的扩展,javascript有的它都有了,javascript没有的,它也都有了。
但是,它还有个问题,就是不能直接在浏览器中裸奔,它得打扮打扮(运行环境)才能出门。
1、安装node
官网下载:
https://nodejs.org/en/
我的环境是win10 64位,所以我下载这个14.17.0LTS版。安装过程就一路回车到结束即可。
2、安装TS
npm install -g typescript
tsc -v // 查看版本号
tsc -v 这个命令可以查看你目录安装的ts版本号,不出意外的话,就间接验证了你已经成功安装了ts的运行环境。
二、编辑器选择
vscode 是首选。一是轻量,二是跟TS 同是微信自家的东西,都是一个妈生的,肯定调教都非常默契,这两在一块绝对不耽误事。
当然,你可以选择webstorm,sublime text,notepad++,atom等编辑器。作为一名现代的码农,你的幸福是无限可能的,选择太多了。
三、第一个TS程序
创建demo.ts文件
内容如下:
let str = "Hello world"
console.log(str)
前面说过了,浏览器是不能直接运行TS程序的,我们第一步,需要把demo.ts文件编译成js代码:
tsc demo.ts
执行完成后,文件夹就多了一个demo.js文件:
这时你就可以像平时玩javascript一样的来玩这个demo.js文件了。我在这里偷个懒,就不把它引入html文件中来运行了,我直接在命令行窗口通过node来跑这个程序:
我们如愿以尝,demo.ts中的程序被成功运行起来了。
四、为vscode 配置自动编译TS代码
这个世界上因为有程序员,才会有各种不可思议的发明和创造(其实是偷懒),为我们的生活带来非常多的便宜。TS程序也是一样,我们不愿意写完TS代码之后,每次都要手动执行tsc xxx.ts
。现在我们来配置TS程序的自动编译。
(一)、生成配置文件
在项目根目录执行以下代码:
PS F:\study\typescript\demo01> tsc --init
message TS6071: Successfully created a tsconfig.json file.
回到目录中,这时多了一个tsconfig.json
文件。它的内容:
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', 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', 'react', 'react-jsx' or 'react-jsxdev'. */
// "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. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
/* 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 */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}
(二)、修改配置
在tsconfig.json文件中,找到以下两项并修改,如果是被注释掉的,请打开注释:
//"outDir": "./js",
"strict": true,
"outDir": "./js",
是编译后的js存放目录,"strict": false,
,把true
改为false
,
(三)、选择VScode 自动编译
1、配置
菜单栏: 终端----> 运行任务 ----> 打开的配置菜单中,用鼠标点击typescript,会展开当前目录,然后选择tsconfig.json
文件即可。
此时,目录下会生成一个.vscode文件夹,里面有和个tasks.json文件。我们打开来看:
{
"version": "2.0.0",
"tasks": [
{
"type": "typescript",
"tsconfig": "demo01/tsconfig.json",
"problemMatcher": [
"$tsc"
],
"group": "build",
"label": "tsc: 构建 - demo01/tsconfig.json"
}
]
}
这个文件就是vscode用来监听ts文件变化并实现自动同步编译的。
2、启动任务
菜单栏: 终端----> 运行任务 输入tsc 回车
如图所示,当你看到这个时,就说明VScode已经启动了自动编译。
现在我们来写点代码试试。
PS:无法重新声明块范围变量"XXX"的问题。
不出所料当你完成了上面的一顿操作,正爽的时候,你发现自己写了无数个习惯性的同名变量,比如str,arr,fn之类的东西时,结果你发现写不下去了。vscode老提示你无法重新声明块范围变量
解决这个问题只需要在你的代码最后加上:
export {};
这是我的demo1.ts的完整内容:
function foo(args:string){
return console.log(args);
}
let str:string = "Holle World ~";
foo(str);
export {};
出现这个问题的原因分析:
1、说明TS的变量不能重复定义(在同一个作用域范围内)
2、TS的作用域是整个项目
3、加上export,你的这个TS文件就是一个模块,模块的内的变量作用域被限定在模块内部。