VSCode搭建node + typescript开发环境

我们一起来喜欢TypeScript

现在写js不用TypeScript,伦家可能会觉得你是外星人。
是的,TypeScript很大程度增强了代码的可读性,可跟踪性,可维护性和减少了bug。
那么没有理由不适用TypeScript进行js开发,但是回归本质,要根据实际出发,不是盲目的一来直接上TS。


我参与过一些使用TS开发的项目,也发现使用TS出现的问题。
举点例子:

  1. 无处不见的any
  2. 无视TS
    高版本的express已经内置TS, 实际上到处还是any。
app.get("/", function(req:  any, res: any) {
    res.send("Hello,"  +  data.name);
});
  1. 本身一个函数能写完的代码,却写一个class来完成
  2. tslint编译一堆错误,依旧无视
    这条倒是其次, 因为很多时候,也许你没有那么多时间去处理这些问题。也说明我们在工程化下的功夫不足。

node和typescript

node + typescript 入门级别的配置真的特别简单。

  1. npm安装typescript
  2. 配置tsconfig.json
  3. 配置package.json的scripts命令

简单三步,你就可以通过简单的一步npm run xxx,TS文件们就乖乖的变为了js文件。
然后执行node dist/xx.js就能启动你的服务了。
但是,这不是我们所期望的。
我们希望我修改ts文件后,自动编译为js文件,然后启动服务。


我了解的相对较好的有下面三种方式:

ts-node-dev

这个方案是无意中看到的,star并不是特别多,400左右。
ts-node-dev 是基于 ts-node 的。
ts-node 可以直接执行ts文件,是不是很酷。
一句代码就可以监听文件变化,并运行编译后的代码。

ts-node-dev --respawn app.ts

我为什么要将Typescript与Express、nodejs一起使用(译文)

TypeScript-Node-Starter

微软这也有一个参考。也有对tslint的支持。
基本思路就是package.json 的scripts。
其主要使用的是 concurrently 和# nodemon
package.json的scripts如下:

  "scripts": {
    "start": "npm run serve",
    "build": "npm run build-sass && npm run build-ts && npm run tslint && npm run copy-static-assets",
    "serve": "node dist/server.js",
    "watch-node": "nodemon dist/server.js",
    "watch": "concurrently -k -p \"[{name}]\" -n \"Sass,TypeScript,Node\" -c \"yellow.bold,cyan.bold,green.bold\" \"npm run watch-sass\" \"npm run watch-ts\" \"npm run watch-node\"",
    "test": "jest --forceExit --coverage --verbose",
    "watch-test": "npm run test -- --watchAll",
    "build-ts": "tsc",
    "watch-ts": "tsc -w",
    "build-sass": "node-sass src/public/css/main.scss dist/public/css/main.css",
    "watch-sass": "node-sass -w src/public/css/main.scss dist/public/css/main.css",
    "tslint": "tslint -c tslint.json -p tsconfig.json",
    "copy-static-assets": "ts-node copyStaticAssets.ts",
    "debug": "npm run build && npm run watch-debug",
    "serve-debug": "nodemon --inspect dist/server.js",
    "watch-debug": "concurrently -k -p \"[{name}]\" -n \"Sass,TypeScript,Node\" -c \"yellow.bold,cyan.bold,green.bold\" \"npm run watch-sass\" \"npm run watch-ts\" \"npm run serve-debug\""
  }

TypeScript with Node.js里面提供了更加简单的方法。 nodemon + ts-node

 "scripts": {
    "start": "npm run build:live",
    "build": "tsc -p .",
    "build:live": "nodemon --watch 'src/**/*.ts' --exec 'ts-node' src/index.ts"
  },

TypeScript-Node-Starter的package.json可以好好看看,具有很好的扩展性。

3. gulp-typescript + gulp-nodemon

gulp-typescript负责编译ts
gulp-nodemon负责启动服务
主要任务就是copy, compile和watch

const gulp = require("gulp");
const ts = require("gulp-typescript");
const nodemon = require('gulp-nodemon')
const del = require('del');
const sourcemaps = require('gulp-sourcemaps');


const tsProject = ts.createProject("tsconfig.json", { noImplicitAny: true });

// 默认任务
gulp.task("default", ["copy", "compile", "watch"], function () {
    console.log('started .....')
})

// 复制配置文件
gulp.task('copy', function () {
    return gulp.src("./src/config/**/*.json")
        .pipe(gulp.dest("./dist/config"))     
})

// 编译
gulp.task("compile", function () {
    return gulp.src("./src/**/*.ts")
        .pipe(sourcemaps.init({ loadMaps: true }))
        .pipe(tsProject())
        .js
        .pipe(sourcemaps.write('./maps'))
        .pipe(gulp.dest("dist"));
})

gulp.task('build',['compile','copy'])


// 删除
gulp.task('del', function (cb) {
    return del([
        'dist/**',
    ], cb);
});

// 监听变化
gulp.task('watch', ['compile'], function (done) {
    var stream = nodemon({
        script: 'dist/app.js',
        watch: 'src/**',
        tasks: ['copy', 'compile'],
        done: done,
        ext: 'ts html json'
    })
    return stream
})

使用typescript开发node js
TypeScript with Node.js


ESLint

到这里,我们已经又进了一步。
VSCode本身有插件TSLint插件,而且有新旧版。
ESLint插件默认是 可以读取tslint.json的配置的,如果没有,他有自己的默认配置。
新版的,如果有错误,默认是警告,而不是错误提示。
你去首选项勾选掉:tslint.alwaysShowRuleFailuresAsWarnings即可。


我们是需要添加eslint.json配置的

  1. 方便自定义
  2. eslint编译检查,比如你的同事是用txt文件编写的呢。

因此,我们还需要安装tslint包。
还需要在package.json的文件里面添加一个脚本

"tslint": "tslint -c tslint.json -p tsconfig.json",

Prettier

代码美化。很多编辑器都有类似功能, VSCode也不例外。
VSCode的Prettier内置了prettier-eslintprettier-tslint插件。
你可以在配置里面json文件修改或者配置面板修改。

"prettier.eslintIntegration": false,

这样一来,Prettier使用的就是tslint的配置。
在这里以后, windows换将下,默认情况,你就可以Ctl + Shift + F 自动格式化代码了。而且是按照你的tslint配置来格式化的, 就问你怕不怕。

总结

我们最后来看一下package.json下scripts的配置

"scripts": {
"build": "npm run tslint && npm run build-ts",
"build-ts": "tsc",
"watch-ts": "tsc -w",
"watch-node": "nodemon dist/app.js",
"tslint": "tslint -c tslint.json -p tsconfig.json",
"dev": "concurrently \\"npm:watch-ts\\"  \\"npm run watch-node\\""
}
  • build: 最终的构建
  • build-ts: 仅仅是build TS文件
  • watch-ts: 文件变化时,就build
  • watch-node: build后的文件变化后,就重启服务
  • tslint: TS语法检查
  • dev: 开发模式下,修改ts文件后,自动build为js文件,并启动服务。

这样一来,感觉轻松多了。
想想就没好,自动美化代码,编写后自动启动服务。
喝点茶,出去走走。

posted @ 2019-03-28 17:12  -云-  阅读(3994)  评论(0编辑  收藏  举报