Typescript之VScode环境搭建(Mac)

Typescript之VScode环境搭建(Mac)



前言

分享并且记录了在vscode环境下编译运行typescript项目


提示:以下是本篇文章正文内容,下面案例可供参考

一、安装Typescript

官方地址:【官方安装typescript】
有两种主要的方式来获取TypeScript工具:

  1. 通过npm(Node.js包管理器)
  2. 安装Visual Studio的TypeScript插件

本文使用方式1安装ts,另外nodejs的mac环境搭建请自行百度

mac终端运行一下命令全局安装typescript:

npm install -g typescript

如果安装成功则运行以下命令查看当前ts版本信息:

tsc -v
Version 4.1.3

二、新建Typescript项目

1.创建名为test文件夹

mkdir -pv test -- 创建目录
cd test -- 切换到目录

2.初始化ts项目

编译项目配置详情查看官方网站:tsconfig.json【详情官网链接】

  • 创建tsconfig.json :
tsc --init  
  • 命令行用vscode打开test项目:
    注意:源vscode的app名称/Applications/Visual Studio Code.app,本人已经重命名了,把中间空格删除。
open -a /Applications/VisualStudioCode.app/ ./  
  • 如图所示test项目下只有tsconfig.json文件

在这里插入图片描述

  • 创建main.ts文件:
touch main.ts
  • 创建outputs文件夹用于存放编译好的js文件
mkdir -pv outputs

3.编辑tsconfig.json文件

  1. 编译使用了target:ES6,module:commonjs;
  2. sourceMap:生成.js.map文件,用于debug调试;
  • 什么是source map文件? source map文件是js文件压缩后,文件的变量名替换对应、变量所在位置等元信息数据文件,一般这种文件和min.js主文件放在同一个目录下。 比如压缩后原变量是map,压缩后通过变量替换规则可能会被替换成a,这时source map文件会记录下这个mapping的信息,这样的好处就是说,在调试的时候,如果有一些JS报错,那么浏览器会通过解析这个map文件来重新merge压缩后的js,使开发者可以用未压缩前的代码来调试,这样会给我们带来很大的方便。
  1. inlineSources:只生成一份.js.map文件,否则会每份ts文件都会生成一份.js.map文件。要先开启sourceMap为true后才可以设置此字段;
  2. outDir:我们设置为"./outputs",把所有编译后的js文件都放在这个文件夹下
  • 配置如下:
{
    
    
  "compilerOptions": {
    
    
    /* Visit https://aka.ms/tsconfig.json to read more about this file */

    /* Basic Options */
    // "incremental": true,                   /* Enable incremental compilation */
    "target": "ES6",                          /* 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', 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. */
    // "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. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    "outDir": "./outputs",                           /* 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 */

    /* 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. */
    /* 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. */
  }
}

4.添加测试代码

1. 编辑main.ts文件添加如下代码:

function main() {
    
    
    console.log("hello world!")    
}
main()

2. 命令行执行以下代码编译且运行

tsc -p ./ && node outputs/main.js
hello world!           //编译执行后的输出

//注释:
tsc -p ./              //编译当前目录下的project,即test/main.ts;
node outputs/main.js   //执行编译好的js文件

3. 最新项目结构如下图所示:
在这里插入图片描述

三、添加vscode的task.json文件

1.cmd+shift+B:

按着cmd+shift+B执行编译指令,但是因为没有配置task.json,vscode并没有执行编译任务,如下图所示:

在这里插入图片描述

vsocde根据你编辑的tsconfig提供了两种编译方式。一种是整个项目build,特点就是慢;另外一种是watch模式,就是通过监听你修改了ts文件,自动后台编译,特点就是快,按照你的需要配置这两种方式,选择一种默认即可,添加其中一种为默认后,按住cmd+shift+B就是执行这种编译操作。

2.添加tsc:bulid - tsconfig.json配置:

点击上图最右边的齿轮按钮添加默认添加了配置,此时项目当中新增了.vscode/task.json;如下图所示:

在这里插入图片描述

3. 添加tsc:watch - tsconfig.json配置:

  1. 在task.json的tasks字段中在添加一份配置,手动编辑在{}后面添加英文逗号(编辑完一定要保存),再点击cmd+shift+P,然后输入config,看见Tasks:configure Default Build Task后回车后,如图所示:
    在这里插入图片描述
  2. 再次见到步骤1图中的两种编译选项,这次选择tsc:watch - tsconfig.json然后回车配置文件更新后,如下图所示:
    在这里插入图片描述
    “isDefault”: true是前文提到的cmd+shift+B时候的默认选择的编译方式,这里选择是watch,用户可以编辑上边的"label": "tsc: build - tsconfig.json"的group字段,可以修改成bulid模式为默认编译方式。

4. 添加编译前依赖配置:

- 追加clean outputs文件夹命令

在实际编写项目的过程中一定会遇到一个问题,就是如果删除了某个文件,outputs下的对应js编译文件没有删掉,可以编译前清理下outputs目录。编辑task.json文件,追加以下配置:

{
    
    
		"label": "clean outputs",
		"type": "shell",
		"command":[				
			"cd ${workspaceFolder} &&",
			"rm -rf outputs &&",
			"mkdir -pv outputs"
		]
}

- 添加dependsOn字段
dependsOn字段传入一个task的标签label入上面清理配置的clean outputs。就可以在执行次命令前添加清理命令,如下图所示:

在这里插入图片描述

5. 添加运行项目配置:

1. 为"tsc: build - tsconfig.json"添加名为"automatically run script"的自动执行 任务

下面添加一个编译后运行的任务:

{
    
    
		"label": "automatically run script",
		"type": "shell",
		"command":"node ${workspaceFolder}/outputs/main.js",
		"dependsOn":["tsc: build - tsconfig.json"],
		"group":{
    
    
			"kind": "build",
			"isDefault": true
		}
},

另外修改上面label为tsc: watch - tsconfig.json的group字段,把"isDefault": true字段删除。因此使用cmd+shift+B执行顺序是以下:
1.“label”: “clean outputs”;
2.“label”: “tsc: build - tsconfig.json”;
3.“label”: “automatically run script”

最新的task.json 如下图所示:
在这里插入图片描述
执行cmd+shift+B,terminal成功输出hello world!
输入如下图所示:
在这里插入图片描述

2 为"tsc: watch - tsconfig.json"添加名为"manually run script"的手动执行任务
如下图所示:

{
    
    
	"label": "manually run script",
	"type": "shell",
	"command":["node ${workspaceFolder}/output/main.js"],
	"group": "test"
}

另外我们需要先把"isDefault": true字段从automatically run script删除,然后添加到tsc: watch - tsconfig.json的group字段中,最新task.json配置表如下图所示:
在这里插入图片描述

执行cmd+shift+B,控制台输出如下图:
在这里插入图片描述
我们在修改main.ts中的代码:

function main() {
    
    
    console.log("hello world!".toUpperCase())    
}

main()

虽然outpus下的main.js也编译更新了,但是terminal没有输出任何值,我们需要添加一个快捷键执行manually run script任务。

1.cmd+K然后左下角显示等待下一个指令;
在这里插入图片描述
2.再输入cmd+S 然后弹出Keyboard Shortcuts的页面这里编辑快捷键;
3.搜索输入"Tasks:run Test task" ;
4.点击前面的编辑按钮,我定义为cmd+ctrl+R,因为cmd+R,以及ctrl+R都有占用了。如下图所示:
在这里插入图片描述
5.执行cmd+ctrl+R,弹出task的名称选择manually run script回车
在这里插入图片描述
6.teminal输出:

在这里插入图片描述


总结

我们运用了vscode的task功能定义了两种编译方式:
  1. tsc build: 我们的起始task是automatically run script,需要用好group下的"isDefault": true字段,使用cmd+shift+B编译项目后自动执行项目;
  2. tsc build watch : 我们先把group的"isDefault": true放在tsc: watch - tsconfig.json的group字段下,然后cmd+shift+B启动后台监听改动自动编译,然后需要手动执行代码manually run script,我们为此添加了快捷键cmd+ctrl+R。另外,退出监听模式是在teminal下按cmd+C然后回车退出。

猜你喜欢

转载自blog.csdn.net/Suarez1987/article/details/111993753