# koa2-ts **Repository Path**: liszter/node-koa2 ## Basic Information - **Project Name**: koa2-ts - **Description**: koa2 搭建后台项目 支持ts - **Primary Language**: JavaScript - **License**: Not specified - **Default Branch**: dev - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2022-04-16 - **Last Updated**: 2024-11-23 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # TypeScript+nodejs开发环境搭建 ## 最终包含的内容 - nodejs+typeScript+ESLint+Prettier+etc - 在nodejs中使用`typeScript` - 在nodejs中使用`import`语法 - 更改代码后**自动重启**node服务器 - 自动编译打包为ts为js文件 - 以koa2为例构建 ## 事前准备 ### 构建环境 确定已经安装了node.js,git以及typeScript 因为本教程使用yarn构建,所以还需要安装yarn,或者使用相对的npm命令 - 检查node版本 ```bash node -v → v16.3.0 ``` - 检测tsc版本(使用npx命令) ```bash npx tsc --version → v4.4.4 ``` - os: windows - 编辑器: vs code ### 初始化`editorconfig` 新建`.editorconfig`,设置编辑器和ide规范 内容根据自己的喜好或者团队规范 ```bash root = true [*.{js,ts,json}] indent_size = 2 charset = utf-8 indent_style = space trim_trailing_whitespace = true insert_final_newline = true ``` ### 初始化`package.json` ```bash yarn init ``` ``` { "name": "node", "version": "1.0.0", "main": "index.js", "license": "MIT" } ``` ## nodejs+typescript开发环境搭建 ### `typescript`依赖安装 安装typeScript的基础依赖包 ```bash yarn add -D typescript @types/node ``` ### 初始化`tsconfig.json` ```bash npx tsc --init ``` 初始化生成的`tsconfig.json`含有许多备注 如果嫌麻烦可以直接使用下面的模板 项目设定根据实际情况填写即可 ```json { "compilerOptions": { "target": "esnext", "module": "commonjs", "sourceMap": true, "outDir": "./dist", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["src"], "exclude": ["node_modules", "dist", "public"] } ``` 这里需要注意一下 - outDir: 是编译后文件放置的文件夹 - include: 是需要检查哪的文件来编译 - exclude: 是不需要检查哪的文件来编译 ### 确认typescript环境 新建文件夹src ``` mkdir src ``` 并且在src内新建index.ts 下面是index.ts,极其极其简单的typescript语句 ```js const msg: string = 'Hello World' console.log(msg) ``` 编译typescript ```dash npx tsc ``` 成功的话,这时会在dist文件内生成一个index.js,内容如下 很显然,ts变成了js ```js "use strict"; const msg = 'Hello World'; console.log(msg); //# sourceMappingURL=app.js.map ``` 使用node命令执行index.js ```bash node dist/index.js → Hello World ``` ## 开发执行脚本配置 ### 安装依赖 ```bash 安装ts-node-dev和npm-run-all yarn add -D ts-node-dev npm-run-all ``` - `ts-node-dev`:开发用依赖,开发时自动编译ts为js并重启node服务器 - `npm-run-all`:一个命令来执行一个以上的脚本命令 ### 配置`package.json`脚本 ```json "main": "dist/index.js", ...省略 "scripts": { "dev": "ts-node-dev --respawn src/index.ts", "resetFolder": "rimraf dist/*", "compile": "tsc", "build": "npm-run-all resetFolder compile", "start": "node ." }, ``` dev:开发的时候用,运行node服务器,伴随代码更改自动重启node服务器 (--respawn 是 ts-node-dev命令选项,想要自动重启必须得加上 ) - resetFolder:清空dist文件夹 - compile:编译typescript - build:清理dist文件夹并编译typescript - start:运行nodejs脚本 到这一步,最基本的typescript+nodejs开发环境就搭建完了 可以试着运行一下上面的命令 ## ESLint + Prettier ### 初始化并配置eslint 安装eslint依赖 ```bash yarn add -D eslint typescript @typescript-eslint/parser @typescript-eslint/eslint-plugin ``` 新建.eslintrc.js文件并写入配置 也可以使用`eslint --init` 生成,但这里方便起见直接复制粘贴了 当然也可以根据喜好导入airbnb或google等配置,这里只是最基础的standard版本 ```js module.exports = { root: true, env: { node: true, es2021: true, }, parser: '@typescript-eslint/parser', parserOptions: { ecmaVersion: 12, sourceType: 'module', tsconfigRootDir: __dirname, project: ['./tsconfig.json'], }, plugins: ['@typescript-eslint'], extends: [ 'eslint:recommended', 'plugin:@typescript-eslint/recommended', 'plugin:@typescript-eslint/recommended-requiring-type-checking', ], } ``` 导入了eslint后,.eslintrc.js会出现如下报错 ``` Parsing error: "parserOptions.project" has been set for @typescript-eslint/parser. ``` 这是由于eslint配置和ts编译配置冲突造成的,解决方法和具体原因详见这里 为了解决问题,在tsconfig.json中加入".eslintrc.js" ```js "include": [ ".eslintrc.js","src"], ...省略 ``` 尝试执行eslint ```bash npx eslint src/index.ts ``` - 初始化并配置prettier ### prettier依赖 ``` yarn add -D prettier eslint-config-prettier ``` 新建.prettier.js文件并写入配置 根据自己的喜好 ```js module.exports = { semi: false, tabWidth: 2, printWidth: 120, proseWrap: 'preserve', singleQuote: true, trailingComma: 'all', } ``` ### 在.eslintrc.js集成prettier ```js extends: [ 'eslint:recommended', 'plugin:@typescript-eslint/recommended', 'plugin:@typescript-eslint/recommended-requiring-type-checking', 'prettier', 'prettier/@typescript-eslint', ], rules: { 'prettier/prettier': 'error', }, ``` 在vs code设置了保存并整理代码的话,适当修改并保存就可以看到prettier效果了 至此,typeScript+nodejs+eslint+prettier的开发环境就已经搭建结束了 下面将以koa.js为例,实际上你也可以使用你喜欢的nodejs框架,比如express.js等 集成koa.js ### 初始化koa ``` yarn add koa ``` 改写index.ts ``` import Koa from 'koa' const app = new Koa() const msg: string = 'Hello World' app.use(async (ctx: Koa.Context): Promise => { ctx.body = msg }) app.listen(7000) ``` 此时会报一些找不到声明文件的错误,所以需要进行下一步,追加声明文件 - 安装koa类型声明文件 ``` yarn add -D @types/koa ``` 找不到声明文件的错误被成功消除 如果今后你要使用路由等koa插件,也需要同时安装该插件的声明文件 ### 运行 这时koa.js的集成也已经完成 运行yarn dev并访问http://localhost:7000 ``` yarn dev ``` 可以发现运行成功,页面上有Hello World ### 打包 运行yarn build会发现dist里面的index.js文件 typeScript已经全都被转换为(不认识的)js文件了 ``` yarn build ``` 到这里`typeScript+koa2+eslint+prettier`的开发环境就已经完全搭建结束了 ## 最后 附赠上完整package.json文件 ```json { "name": "node", "version": "1.0.0", "main": "dist/index.js", "license": "MIT", "scripts": { "dev": "ts-node-dev --respawn src/index.ts", "resetFolder": "rimraf dist/*", "compile": "tsc", "build": "npm-run-all resetFolder compile", "start": "node ." }, "dependencies": { "koa": "^2.13.4" }, "devDependencies": { "@types/koa": "^2.13.4", "@types/node": "^17.0.16", "@typescript-eslint/eslint-plugin": "^5.11.0", "@typescript-eslint/parser": "^5.11.0", "eslint": "^8.8.0", "eslint-config-prettier": "^8.3.0", "npm-run-all": "^4.1.5", "prettier": "^2.5.1", "ts-node-dev": "^1.1.8", "typescript": "^4.5.5" } } ```