Este repositório contém um conjunto de configurações e dependências para a criação de um ambiente de desenvolvimento de back-end utilizando o framework Express e o TypeScript. O objetivo é fornecer um ponto de partida sólido para projetos back-end, com integrações de ferramentas de linting, formatação de código e boas práticas de commits.
- Express - framework para criação de aplicativos web.
- Typescript - superset, linguagem baseada em javascript
- ESLint - Ferramenta de linting para identificar e corrigir problemas no código.
- Prettier - Formatador de código que mantém um estilo de código consistente.
- Lint-Staged - executa scripts de linting e formatação de código em arquivos no momento do commit.
- Husky - Integração com o Git para automatizar tarefas antes dos commits.
- Commitlint - Verifica se as mensagens de commit seguem convenções definidas.
- Jest - Framework de teste para JavaScript e TypeScript.
Para baixar, executar e modificar o projeto, você precisa ter instalado em sua máquina:
- Clone o repositório
git clone https://github.com/aleretamero/setup_express.git
- Acesse a pasta do projeto
cd setup_express
- Instale as dependências
npm install
# ou
pnpm install
# ou
yarn install
Foto | Nome |
---|---|
![]() |
Alexandre Retamero |
- Iniciar o projeto
git init
npm init -y
- Instalar o TypeScript
npm install -D typescript @types/node
npx tsc --init
- Instalar nodemon e ts-node
npm install -D ts-node nodemon
- Instalar prettier e eslint
npm install -D prettier eslint eslint-config-prettier
npx eslint --init
1. How would you like to use ESLint?
- To check syntax and find problems
2. What type of modules does your project use?
- JavaScript modules (import/export)
3. Which framework does your project use?
- None of these
4. Does your project use TypeScript?
- Yes
5. Where does your code run?
- Node
6. What format do you want your config file to be in?
- JSON
7. Would you like to install them now?
- Yes
8. Which package manager do you want to use?
- npm
- Instalar husky a lint-staged
npm install -D husky lint-staged
- Instalar Jest
npm install -D jest @types/jest ts-jest
npx jest --init
1. Would you like to use Jest when running "test" script in "package.json"?
- Yes
2. Would you like to use Typescript for the configuration file?
- Yes
3. Choose the test environment that will be used for testing
- node
4. Do you want Jest to add coverage reports?
- Yes
5. Which provider should be used to instrument code for coverage?
- v8
6. Automatically clear mock calls, instances, contexts and results before every test?
- Yes
- Instalar commitlint
npm install -D @commitlint/config-conventional @commitlint/cli
- Setup básico Express
npm install express
npm install -D @types/express
mkdir src
mkdir .husky
- Criar arquivo index.ts
ni src/index.ts # powershell
# ou
touch src/index.ts # bash, zsh
import express from 'express';
const app = express();
app.get('/', (_req, res) => {
res.status(200).send('Hello world!');
});
app.listen(3333, () => {
console.log('Server running on PORT 3333');
});
- Criar arquivo index.spec.ts
ni src/sum.spec.ts # powershell
# ou
touch src/sum.spec.ts # bash, zsh
it('should sum', () => {
expect(2 + 2).toBe(4);
});
- Criar arquivo .gitignore
ni .gitignore # powershell
# ou
touch .gitignore # bash, zsh
node_modules
coverage
dist
build
.env
- Criar arquivo .gitattributes
ni .gitattributes # powershell
# ou
touch .gitattributes # bash, zsh
* text=auto eol=lf
- Criar arquivo .lintstagedrc.json
ni .lintstagedrc.json # powershell
# ou
touch .lintstagedrc.json # bash, zsh
{
"*.ts": [
"eslint 'src/**' --fix",
"prettier --check 'src/**'",
"npm run test:staged"
]
}
- Criar arquivo commitlint.config.js
ni commitlint.config.js # powershell
# ou
touch commitlint.config.js # bash, zsh
module.exports = { extends: ['@commitlint/config-conventional'] };
- Configurar tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"rootDir": "./src",
"outDir": "./dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
},
"exclude": [
"jest.config.ts",
"commitlint.config.js",
"./node_modules",
"./dist",
"./coverage"
]
}
ni tsconfig.eslint.json # powershell
# ou
touch tsconfig.eslint.json # bash, zsh
{
"extends": "./tsconfig.json",
"include": ["src/**/*.ts", "jest.config.ts", "commitlint.config.js"],
"exclude": ["./node_modules", "./dist", "./coverage"]
}
- Configurar jest.config.ts
import type { Config } from 'jest';
const config: Config = {
clearMocks: true,
collectCoverage: true,
collectCoverageFrom: ['<rootDir>/src/**/*.ts'],
coverageDirectory: 'coverage',
coveragePathIgnorePatterns: ['/node_modules/'],
coverageProvider: 'v8',
roots: ['<rootDir>/src'],
testEnvironment: 'node',
transform: {
'.+\\.ts$': ['ts-jest', { isolatedModules: true }],
},
};
export default config;
- Configurar .eslintrc.json
{
"env": {
"es2021": true,
"node": true,
"jest": true
},
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"prettier"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module",
"project": ["./tsconfig.eslint.json"]
},
"plugins": ["@typescript-eslint"],
"overrides": [
{
"files": ["./src/**/*.ts", "./node_modules", "./dist", "./coverage"],
"parserOptions": {
"project": "./tsconfig.eslint.json"
}
}
],
"rules": {}
}
- Criar arquivo .prettierrc.json
ni .prettierrc.json # powershell
# ou
touch .prettierrc.json # bash, zsh
{
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"bracketSpacing": true,
"arrowParens": "always",
"trailingComma": "all",
"printWidth": 80,
"useTabs": false,
"endOfLine": "lf"
}
- Criar scripts no package.json
{
"scripts": {
"start": "node dist/index.js",
"build": "tsc",
"start:dev": "nodemon --exec ts-node ./src/index.ts",
"prepare": "husky install",
"lint": "eslint src/**/*.ts --fix",
"format": "prettier --write src/**/*.ts",
"test": "jest --passWithNoTests",
"test:watch": "npm test -- --watch --onlyChanged",
"test:staged": "npm test -- --findRelatedTests",
"test:push": "npm test -- --coverage"
}
}
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit ${1}'
npx husky add .husky/pre-push "npm run test:push"
npx husky add .husky/pre-commit "npx lint-staged"
npm run prepare