Nestjs最佳实践教程:1编码环境搭建

另,本人在找工作中,希望能有远程工作匹配(无法去外地),有需要的老板可以看一下我的个人介绍:pincman.com/about

注意: 为了兼顾大多数用户,本教程使用远程SSH连接Debian服务器进行讲解,同时会给出MacOS的命令,windows本地开发者请自行安装wsl2作为替代

学习目标

  • 安装与配置node.js+pnpm环境
  • 配置tsconfig.json+eslint+prettier实现代码规范化
  • 配置vscode实现调试与在保存代码时自动运行eslint+prettier
  • 配置lanunch.json进行应用调试
  • 安装Thunder Client插件进行接口调试

环境搭建

安装与配置node.js环境

MacOS请使用brew安装,如果没有安装brew请先安装

建议:安装到GLOBAL里面的东西统一使用一个包管理器,我这里使用pnpm

安装node.js

# 下载并解压node
~ sudo wget https://nodejs.org/dist/v18.4.0/node-v18.4.0-linux-x64.tar.xz -O /usr/local/src/node18.tar.xz
~ sudo tar -xf /usr/local/src/node18.tar.xz -C /usr/local/
~ sudo mv /usr/local/node-v18.4.0-linux-x64 /usr/local/node
# 添加到环境变量
echo "export PATH=/usr/local/node/bin:\$PATH" >> ~/.zshrc && source ~/.zshrc

配置npm淘宝镜像

~ npm config set registry https://registry.npmmirror.com/

安装pnpm以及初始化pnpm

~ npm install -g pnpm
~ pnpm setup && source .zshrc

配置pnpm淘宝镜像

~ pnpm config set registry https://registry.npmmirror.com/

安装镜像管理工具

~ pnpm add nrm -g 

建议安装一个node版本管理工具比如n或者nvm

因为我们使用普通用户编程,所以把n的目录通过环境变量改成我们可以操作的目录

~ pnpm add n -g 
~ echo "\nexport N_PREFIX=\$HOME/.n" >> ~/.zshrc
~ echo "export PATH=\$N_PREFIX/bin:\$PATH" >> ~/.zshrc
~ source ~/.zshrc
# 安装最新的长期支持版
~ n lts_latest && node --version
# 切换回最新版
~ n latest && node --version

安装nestjs cli

~ pnpm add @nestjs/cli -g

创建项目,我们命名为nestplus

这一步如果出现错误就进入nestplus目录,手动pnpm i一下

~ nest new nestplus # 创建的时候选择pnpm

升级所有包到最新版本

~ pnpm up -latest

这是会报缺少peer建议依赖webpack的警告,把下面这段添加到package.json中就可以了

 "pnpm": {
    "peerDependencyRules": {
      "ignoreMissing": [
        "webpack"
      ]
    }
  }

代码规范化

具体代码与配置请自行查看源代码

代码风格

配置airbnb的eslint规则并整合prettier,并且经过一定的客制化同时配合vscode可达到完美的编码体验

pnpm add typescript \
eslint \
prettier \
@typescript-eslint/parser \
@typescript-eslint/eslint-plugin \
eslint-config-airbnb-base \
eslint-config-airbnb-typescript \
eslint-config-prettier \
eslint-plugin-import \
eslint-plugin-prettier \
eslint-plugin-unused-imports \
eslint-plugin-unused-imports \
prettier-plugin-organize-imports \
eslint-plugin-jest -D

配置内容

...
plugins: ['@typescript-eslint', 'jest', 'prettier', 'import', 'unused-imports'],
extends: [
    // airbnb规范
    'airbnb-base',
    // 兼容typescript的airbnb规范
    'airbnb-typescript/base',
    // typescript的eslint插件
    'plugin:@typescript-eslint/recommended',
    'plugin:@typescript-eslint/recommended-requiring-type-checking',

    // 支持jest
    'plugin:jest/recommended',
    // 使用prettier格式化代码
    'prettier',
    // 整合typescript-eslint与prettier
    'plugin:prettier/recommended',
],

一些重要的规则

其余配置自行查看代码

设置解析文件为tsconfig.eslint.json(我们在Tsconfig配置部分新增这个文件)

parserOptions: {
    project: 'tsconfig.eslint.json',
    tsconfigRootDir: __dirname,
    ecmaVersion: 'latest',
    sourceType: 'module',
},

eslint-plugin-unused-imports用于自动删除未使用的导入

...
 'no-unused-vars': 0,
 '@typescript-eslint/no-unused-vars': 0,
 'unused-imports/no-unused-imports': 1,
 'unused-imports/no-unused-vars': [
    'error',
    {
        vars: 'all',
        args: 'none',
        ignoreRestSiblings: true,
    },
]

import插件,import/order可以按照自己的需求配置

// 导入模块的顺序
'import/order': [
     'error',
     {
         pathGroups: [
             {
                 pattern: '@/**',
                 group: 'external',
                 position: 'after',
             },
         ],
         alphabetize: { order: 'asc', caseInsensitive: false },
         'newlines-between': 'always-and-inside-groups',
         warnOnUnassignedImports: true,
     },
],
// 导入的依赖不必一定要在dependencies的文件
'import/no-extraneous-dependencies': [
    'error',
     {
         devDependencies: [
             '**/*.test.{ts,js}',
             '**/*.spec.{ts,js}',
             './test/**.{ts,js}',
             './scripts/**/*.{ts,js}',
         ],
     },
],

接下来需要配置一下.prettierrc,和.editorconfig,并且把一些它们各自需要忽略的目录和文件分别添加到.eslintignore.prettierignore

最后把git仓库需要忽略的目录和文件写入.gitignore

Tsconfig配置

tsconfig.json文件中添加ESNEXT就可以使用最新的ES语法,并且添加一个@作为根目录映射符

{
    "compilerOptions": {
        // ...
        "paths": {
            "@/*": ["src/*"]
        }
    },
     "include": ["src", "test", "typings/**/*.d.ts"]
}

在跟目录添加一个tsconfig.eslint.json文件,供eslint使用

{
    "extends": "./tsconfig.json",
    "includes": ["src", "test", "typings/**/*.d.ts", "**.js"]
}

tsconfig.build.json中排除**.js

{
    "extends": "./tsconfig.json",
    "exclude": ["node_modules", "dist", "test", "**/*spec.ts"]
}

开发工具

对于node.js,typescript,前端等技术最好的开发工具毋庸置疑的就是vscode,任何其它选项(包括vim,emacs,sublime text,atom,webstorm等等)都有这样那样的问题需要去耗费精力,所以建议直接使用VScode进行开发

VSCode已经自带同步配置和插件的功能,建议启用

安装vscode

Windows直接点击安装包就可以,需要注意的是如果是WSL2或远程SSH开发,需要在远程再一次安装插件

~ brew install vscode

安装eslint插件和prettier插件

~ code --install-extension dbaeumer.vscode-eslint \
  && code esbenp.prettier-vscode

cmd+,选择偏好设置->工作空间,配置eslint插件

{
    "editor.formatOnSave": false,
    "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true
    }
}

shift+cmd+d创建lanunch.json,并且使用ts-node+tsconfig-paths配置断点调试,打好断点,按F5就可以进行调试

这种调试方式适合简单使用,后续我们将会讲到jest测试调试,这样效果会更好

{
    // 使用 IntelliSense 了解相关属性。
    // 悬停以查看现有属性的描述。
    // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "debug nestplus",
            "request": "launch",
            "runtimeArgs": ["run-script", "start:debug"],
            "autoAttachChildProcesses": true,
            "console": "integratedTerminal",
            "runtimeExecutable": "pnpm",
            "skipFiles": ["<node_internals>/**"],
            "type": "pwa-node"
        }
    ]
}

最后安装Thunder Client用于接口测试,当然你也可以安装postman

至此,所有配置完成,现在重启vscode就可以进入下一节学习如何愉快的使用nestjs构建应用了

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!