在开发Node.js项目时,经常需要进行各种设置,比如TypeScript, Jest, ESLint, Prettier等。下面就集中总结一下。下面的总结主要参考了Leo Roese的这个Video。

VS Code 配置
建议安装以下插件:
- vscode-icons
创建项目
mkdir ts-backend
cd ts-backend
创建文件.gitignore:
node_modules
dist
coverage
.env
然后运行:
yarn init -y
文件package.json将被创建:
{
"name": "ts-backend",
"version": "1.0.0",
"main": "index.js",
"license": "MIT"
}
创建文件.nvmrc来指定Node.js版本:
v14.17.3
TypeScript
运行如下命令来安装相关的包:
yarn add -D typescript ts-node @types/node
运行如下命令创建tsconfig.json:
npx tsc --init
ESLint
VS Code插件ESLint
在VS Code中安装ESLint插件。
eslint依赖包
在项目中添加依赖:
yarn add -D eslint
eslint配置文件
创建eslint的配置文件:
npx eslint --init
选择如下:
- To check syntax, find problems, and enforce code style
- JavaScript modules (import/export)
- None of these
- Does your project use TypeScript? Yes
- Where does your code run? Node
- Use a popular style guide: Airbnb
- What format do you want your config file to be in? JavaScript
- Would you like to install them now with npm? Yes
接下来就会创建eslint配置文件.eslintrc.js:
module.exports = {
env: {
es2021: true,
node: true,
},
extends: [
'airbnb-base',
],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
},
plugins: [
'@typescript-eslint',
],
rules: {
},
};
.eslintignore
创建.eslintignore:
node_modules
dist
coverage
.env
Prettier
安装VS Code插件
首先在VS Code中安装插件Prettier。
安装prettier包
接下来安装包:
yarn add -D prettier
创建配置文件.prettierrc
{
"tabWidth": 2,
"printWidth": 120,
"singleQuote": true,
"trailingComma": "es5",
"arrowParens": "avoid",
"semi": true
}
更新eslint配置使两者协同工作
首先安装依赖包:
yarn add -D eslint-plugin-prettier eslint-config-prettier
同时安装以下依赖库:
yarn add -D eslint-import-resolver-typescript tsconfig-paths
然后更新.eslintrc.js:
const newLocal = 'module';
module.exports = {
env: {
es2021: true,
node: true,
},
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'airbnb-base',
'plugin:prettier/recommended',
'plugin:import/errors',
'plugin:import/warnings',
'plugin:import/typescript',
],
parser: '@typescript-eslint/parser',
parserOptions: {
// ecmaVersion: 'latest',
ecmaVersion: 12,
sourceType: newLocal,
},
plugins: ['@typescript-eslint', 'prettier', 'import'],
rules: {
'prettier/prettier': [
'error',
{
endOfLine: 'auto',
},
],
'import/extensions': 'off',
'no-console': 'off',
'import/order': [
'error',
{
'newlines-between': 'never',
groups: [
['builtin', 'external'],
['internal', 'parent', 'sibling', 'index'],
],
},
],
},
settings: {
'import/parsers': {
'@typescript-eslint/parser': ['.ts'],
},
'import/resolver': {
typescript: {
// always try to resolve types under `<root>@types` even it doesn't contain any source code.
alwaysTryTypes: true,
project: './tsconfig.json',
},
},
},
};
Nodemon
安装依赖库:
yarn add -D nodemon
添加nodemon.json:
{
"watch": ["src"],
"ext": "ts,js,json",
"ignore": ["node_modules", "coverage", "dist"],
"exec": "ts-node -r tsconfig-paths/register ./src/index.ts",
"restartable": "rs",
"env": {
"NODE_ENV": "development"
}
}
上面配置中的”rs”意味着,当nodemon运行时,键入”rs”会重新启动应用。
关于环境变量
安装依赖库:
yarn add dotenv-safe
yarn add -D @types/dotenv-safe
添加.env (在.gitignore中已经声明,因此不会被提交):
MYUSERNAME=my_user_name
MYPASSWORD=my_password
同时最好创建一个.env.sample:
MYUSERNAME=
MYPASSWORD=
要想在TS中访问环境变量:
import dotenv from 'dotenv-safe';
dotenv.config();
console.log(process.env.MYUSERNAME);
console.log(process.env.MYPASSWORD);
Jest
安装依赖库
yarn add -D jest ts-jest @types/jest
创建Jest配置文件
npx ts-jest config:init
更新jest.config.js:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
coverageDirectory: 'coverage',
collectCoverageFrom: ['src/**/*.{js,ts}'],
coverageThreshold: {
global: {
branches: 0,
functions: 0,
lines: 0,
statements: 0
},
},
moduleNameMapper: {
'src/(.*)': '<rootDir>/src/$1',
},
moduleDirectories: ['node_modules', 'src'],
};
更新.eslintrc.js
在env中添加jest:
env: {
es2021: true,
node: true,
jest: true,
},
在添加测试用例文件的时候,有两个选择:
- 在__tests__目录中添加
- 添加xxx.test.ts
添加tsconfig.prod.json
{
"extends": "./tsconfig",
"exclude": ["__test__/*", "**/*.test.ts", "**/*.mock.ts"]
}
同时需要更改package.json中的对应script:
"build": "tsc -p tsconfig.prod.json",
配置serverless / TypeScript项目
安装依赖库
yarn add aws-lambda
yarn add -D serverless @types/serverless @types/aws-lambda serverless-plugin-typescript
更新tsconfig.json
然后再tsconfig.json中删除以下两行:
"outDir": "dist",
"rootDir": ".",
serverless.yml
然后创建目录src/functions,以后的Lambda TS源代码就会放在这里。
同时创建serverless.yml
service: lcoding-backend
frameworkVersion: '2'
provider:
name: aws
runtime: nodejs14.x
lambdaHashingVersion: 20201221
stage: dev
region: eu-west-1
functions:
hello:
handler: src/functions/hello.handler
events:
- http:
path: api/hello
method: get
需要在.eslintrc.js中增加新的规则:
rules: {
// ...
'import/prefer-default-export': 'off',
// ...
}
Lambda代码
增加新的代码src/functions/hello.ts:
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
export const handler = async (_event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
try {
const response = {
statusCode: 200,
body: 'Hello serverless',
};
console.log(_event.body);
return response;
} catch (error) {
return {
statusCode: 500,
body: 'An error occured',
};
}
};
部署
部署到开发环境:
sls deploy -s dev
使用serverless-offline
添加serverless-offline
yarn add -D serverless-offline
更新serverless.yml:
plugins:
- serverless-plugin-typescript
- serverless-offline
```
更新package.json
``` json
"scripts": {
"local": "sls offline -s dev",
"dev": "sls -s dev",
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage"
},
VS Code中的Debug
如果想要在VS Code中调试Lamba,添加launch.json:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Serverless Offline",
"program": "${workspaceFolder}/node_modules/serverless/bin/serverless",
"args": ["offline", "start", "--httpPort", "4000", "--noTimeout"],
"protocol": "inspector",
"runtimeExecutable": "node",
"env": {}, // in case env variables are needed
"windows": {
"program": "${workspaceFolder}/node_modules/serverless/bin/serverless"
}
}
]
}