分享并且记录了在vscode环境下编译运行typescript项目
提示:以下是本篇文章正文内容,下面案例可供参考
官方地址:【官方安装typescript】
有两种主要的方式来获取TypeScript工具:
本文使用方式1安装ts,另外nodejs的mac环境搭建请自行百度
mac终端运行一下命令全局安装typescript:
npm install -g typescript
如果安装成功则运行以下命令查看当前ts版本信息:
tsc -v
Version 4.1.3
mkdir -pv test -- 创建目录
cd test -- 切换到目录
编译项目配置详情查看官方网站:tsconfig.json【详情官网链接】
tsc --init
open -a /Applications/VisualStudioCode.app/ ./
touch main.ts
mkdir -pv outputs
{
"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. */
}
}
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文件
按着cmd+shift+B执行编译指令,但是因为没有配置task.json,vscode并没有执行编译任务,如下图所示:
vsocde根据你编辑的tsconfig提供了两种编译方式。一种是整个项目build,特点就是慢;另外一种是watch模式,就是通过监听你修改了ts文件,自动后台编译,特点就是快,按照你的需要配置这两种方式,选择一种默认即可,添加其中一种为默认后,按住cmd+shift+B就是执行这种编译操作。
点击上图最右边的齿轮按钮添加默认添加了配置,此时项目当中新增了.vscode/task.json;如下图所示:
- 追加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。就可以在执行次命令前添加清理命令,如下图所示:
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输出: