## Introduction
在這篇文章中,我會示範如何建立一個新的 Express.js 專案,並整合 ESM、TypeScript、Jest、Prettier、ESLint 和 Path alias。
你可以手動完成這些步驟,或是使用 `gen-express-cli` 指令來生成一個新專案。
```bash
npx gen-express-cli@latest <project-name>
```
## Step 1 - Create a new project
首先,使用以下命令創建一個新專案:
```bash
mkdir express-project
cd express-project
npm init -y
```
## Step 2 - Install dependencies
將以下程式碼貼到你的 `package.json` 文件中:
```json title="package.json"
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "cross-env NODE_ENV=development nodemon -r tsconfig-paths/register --exec ts-node ./src/index.ts --files",
"start": "cross-env NODE_ENV=production node ./build/src/index.js",
"build": "tsc && tsc-alias",
"lint": "eslint ./src/**/*.ts --fix",
"format": "prettier --write ./**/*.{ts,json}",
"test": "jest --coverage=true -w=1 --forceExit --detectOpenHandles --watchAll=false --testPathPattern=src/__tests__ --testPathIgnorePatterns=build"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2",
"dotenv": "^16",
"express": "^4"
},
"devDependencies": {
"cross-env": "^7",
"nodemon": "^3",
"typescript": "~5.3",
"ts-node": "^10",
"@types/cors": "^2",
"@types/express": "^4",
"@types/node": "^20",
"eslint": "^8",
"eslint-config-prettier": "^9",
"eslint-config-standard-with-typescript": "^43",
"eslint-plugin-import": "^2",
"eslint-plugin-n": "^16",
"eslint-plugin-prettier": "^5",
"eslint-plugin-promise": "^6",
"@typescript-eslint/eslint-plugin": "^6",
"eslint-plugin-jest": "^27",
"prettier": "^3",
"jest": "^29",
"ts-jest": "^29",
"@types/jest": "^29",
"tsc-alias": "^1",
"tsconfig-paths": "^4",
"typescript-transform-paths": "^3"
}
}
```
然後安裝套件:
```bash
npm install
```
## Step 3 - Create a index.ts file
創建一個名為 `src/index.ts` 的文件,並貼上以下程式碼:
```typescript title="src/index.ts"
import express from 'express';
import dotenv from 'dotenv';
import cors from 'cors';
dotenv.config();
const app = express();
const PORT = process.env.PORT ?? 8000;
app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
export default app;
```
## Step 4 - Setup TypeScript
創建一個名為 `tsconfig.json` 的文件,並貼上以下程式碼:
```json title="tsconfig.json"
{
"compilerOptions": {
"target": "es6",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"resolveJsonModule": true,
"baseUrl": ".",
"outDir": "build",
"sourceMap": true,
"strict": true,
"esModuleInterop": true,
"types": ["node", "jest"],
"plugins": [
{
"transform": "typescript-transform-paths"
},
{
"transform": "typescript-transform-paths",
"afterDeclarations": true
}
],
"paths": {
"@/*": ["src/*"]
}
},
"include": ["process.env.d.ts", "./**/*.ts"],
"exclude": ["node_modules"]
}
```
## Step 5 - Setup ESLint and Prettier
創建一個名為 `.eslintrc.json` 的文件,並貼上以下程式碼:
```json title=".eslintrc.json"
{
"env": {
"es2021": true,
"node": true,
"jest/globals": true
},
"extends": ["standard-with-typescript", "prettier"],
"plugins": ["jest", "prettier"],
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"rules": {
"prettier/prettier": [
"error",
{
"semi": true,
"tabWidth": 2,
"printWidth": 140,
"singleQuote": true,
"bracketSameLine": false,
"trailingComma": "all",
"arrowParens": "always"
}
]
}
}
```
再創建一個名為 `.prettierrc` 的新文件,並加入以下程式碼:
```json title=".prettierrc"
{
"semi": true,
"printWidth": 140,
"tabWidth": 2,
"singleQuote": true,
"bracketSpacing": true,
"trailingComma": "all",
"arrowParens": "always"
}
```
## Step 6 - Setup Jest
創建一個名為 `jest.config.ts` 的檔案,並加入以下程式碼:
```javascript title="jest.config.ts"
import type { JestConfigWithTsJest } from 'ts-jest';
const config: JestConfigWithTsJest = {
verbose: true,
transform: {
'^.+\\.ts?$': [
'ts-jest',
{
useESM: true
}
]
},
extensionsToTreatAsEsm: ['.ts'],
moduleNameMapper: {
'^(\\.{1,2}/.*)\\.js$': '$1',
'@/(.*)': ['<rootDir>/src/$1']
}
};
export default config;
```
## Step 7 - Test your project
你可以執行下面的指令來進入開發模式
```bash
npm run dev
```
打開瀏覽器並訪問 `http://localhost:8000`,你會看到 Hello World。
如果要編譯你的 TypeScript 程式碼並進入生產模式,可以執行以下命令:
```bash
npm run build
npm run start
```
要 lint 或 format 你的程式碼可以執行以下指令
```bash
npm run lint
npm run format
```
要執行測試可以執行以下指令
```bash
npm run test
```
如果要 import module,建議使用 @ 來進行 import
```typescript
import <module_name> from '@/module_name'; // recommended
import <module_name> from '../../../module_name'; // not recommended
```
## Conclusion
如果你喜歡這個專案和教學,可以到 [GitHub](https://github.com/RulerChen/gen-express-cli) 上給我一顆星星,如果有任何意見也歡迎提出 issue。