使用TypeScript来编写Node项目

约 3 分钟阅读
TypeScript
Nodejs

之前一篇文章介绍了Nodejs:为什么要学习Nodejs,那么这篇文章我们来做学习Node之前的准备,使用TypeScript编写Node项目。

对于TypeScript就不用再多说了,我已经在很多文章中都提到了TypeScript,现在我是能使用TypeScript就尽量使用TypeScript,因为TypeScript已经是一种趋势,一种必然。

最近在学习Nodejs,就想着使用TypeScript来编写Node相关的东西。

image-20200922234849383

@types/node包的周下载量来看,使用TypeScript编写Node项目的工程是非常的多。

1. 步骤

1、新建一个项目文件夹,并且在文件夹中创建一个src文件夹,在其下面创建一个app.ts文件。

2、回到项目文件夹根目录,运行npm init --yes,直接生成package.json文件,也可以不加yes,手动填写项目的信息。

3、运行npm i typescript --save-dev

4、全局安装两个库:

Terminal window
npm install nodemon ts-node -g

5、在根目录下创建tsconfig.json

{
"compilerOptions": {
"module": "CommonJS",
"target": "ES2015",
"noImplicitAny": false,
"strictNullChecks": true,
"strict": true,
"alwaysStrict": true,
"sourceMap": false,
"noImplicitReturns": true,
"noImplicitThis": true,
"pretty": true,
"listFiles": true,
"listEmittedFiles": true,
"lib": [
"ESNext"
],
"typeRoots": [
"./node_modules/@types"
]
},
"include": [
"./**/*"
],
"exclude": [
"node_modules",
"**/*.spec.ts",
"*.js"
]
}

6、项目结构

Terminal window
package-lock.json
package.json
tsconfig.json
└─src
app.ts

7、最后一步,在package.json文件scripts中,添加"start": "nodemon -e ts,tsx --exec ts-node src/app.ts",

"scripts": {
"start": "nodemon -e ts,tsx --exec ts-node src/app.ts",
},

然后使用npm run start,就可以开始愉快的使用TypeScript编写Node项目了,同时还支持热更新,你每次修改代码时会自动帮你重启项目。

8、如果要使用Node的库,需要引入:

Terminal window
npm i @types/node --save-dev

2. Tslint

代码风格检测工具,虽然Tslint现在开始逐步不再维护,官方也推荐使用Eslint,但是社区还是拥有很高周下载量。

image-20200922234202136

引入包:

Terminal window
npm install tslint tslint-config-prettier --save-dev

在项目的根目录下输入tslint --init,会生成一个tslint.json文件,将文件编辑为:

{
"defaultSeverity": "error",
"extends": [
"tslint:latest",
"tslint-config-prettier"
],
"jsRules": {},
"rules": {},
"rulesDirectory": []
}

这下就完成了Tslint的配置。

3. Eslint

现在Tslint官方大力推广Eslint,所以在这里给出最新的引入Eslint的方法。

这里使用的是Eslint+Prettier。之前使用过Airbnb的规则,发现有些特别不爽的地方,因为我还是喜欢使用双引号,而Prettier,完全符合我的喜好,再加上Prettier格式化插件,代码风格直接上天。

因为我使用的是TypeScript,所以这里要对TypeScript进行检测:

Terminal window
npm install @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint eslint-config-prettier eslint-plugin-prettier prettier --save-dev

首先一股脑的将所有用到的包安装好。

然后在根目录下创建一个.eslintrc.js文件:

module.exports = {
env: {
browser: true,
es2021: true,
},
extends: [
"prettier",
"prettier/@typescript-eslint",
"plugin:prettier/recommended",
],
parser: "@typescript-eslint/parser",
parserOptions: {
ecmaVersion: 12,
sourceType: "module",
},
plugins: ["@typescript-eslint"],
rules: {},
};

完成收工!

转载协议

本文采用 CC BY-NC-SA 4.0 协议进行许可,转载请注明出处。

允许转载、修改和分享,但必须注明作者和出处,且不得用于商业用途,衍生作品需采用相同协议。