Skip to content

Commit 38dccc8

Browse files
committed
feat: update scaffolding for project
1 parent 6b5a1d7 commit 38dccc8

File tree

10 files changed

+347
-633
lines changed

10 files changed

+347
-633
lines changed

README.md

+10-2
Original file line numberDiff line numberDiff line change
@@ -81,9 +81,17 @@ The project uses Prisma as the intelligent ORM tool by default. Supports `Postgr
8181

8282
#### About Environments
8383

84-
- **Development Mode** (`NODE_ENV=development`): read configurations from `configs/constants/development.ts` file, but it will still be overwritten by `.env` file.
84+
When nodejs is running, `ENV` does not mean `NODE_ENV`:
8585

86-
- **Production Mode** (`NODE_ENV=production`): read configurations from `configs/constants/production.ts` file, but it will still be overwritten by `.env` file.
86+
- After NodeJS project is built, we always run it as `NODE_ENV=PRODUCTION`, which may affect some framework optimizations.
87+
- `NODE_ENV` only identifies the NodeJS runtime, independent of the business.
88+
- You should use `ENV` to identify the environment.
89+
90+
For the data settings of each environment, you can refer to the following:
91+
92+
- **Development Mode** (`ENV=development`): read configurations from `configs/constants/development.ts` file, but it will still be overwritten by `.env` file.
93+
94+
- **Production Mode** (`ENV=production`): read configurations from `configs/constants/production.ts` file, but it will still be overwritten by `.env` file.
8795

8896
---
8997

README_CN.md

+10-2
Original file line numberDiff line numberDiff line change
@@ -81,9 +81,17 @@
8181

8282
### 关于环境变量
8383

84-
- **在开发环境中** (`NODE_ENV=development`):自动从文件 `configs/constants/development.ts` 读取配置。
84+
在 NodeJS 运行中,`ENV` 并不等于 `NODE_ENV`
8585

86-
- **在生产环境中** (`NODE_ENV=production`): 自动从文件 `configs/constants/production.ts` 读取配置。
86+
- 当 NodeJS 项目被 build 后 (如在服务端运行),总是设置 `NODE_ENV=PRODUCTION`,这会影响一些第三方库的优化。
87+
- `NODE_ENV` 只用于鉴别 NodeJS 运行,与你的业务环境无关。
88+
- 推荐你总是使用 `ENV` 来鉴别当前的环境。
89+
90+
对于每个环境的数据设置,可以参考如下:
91+
92+
- **在开发环境中** (`ENV=development`):自动从文件 `configs/constants/development.ts` 读取配置。
93+
94+
- **在生产环境中** (`ENV=production`): 自动从文件 `configs/constants/production.ts` 读取配置。
8795

8896
- **任何环境**: 如果 `.env` 文件内存在同名常量,会覆盖上述 2 个环境配置文件。优先级最高。
8997

build.js

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
const { nodeExternalsPlugin } = require('esbuild-node-externals')
2+
3+
require('esbuild')
4+
.build({
5+
entryPoints: ['app.ts'],
6+
bundle: true,
7+
outfile: 'dist/index.js',
8+
platform: 'node',
9+
plugins: [
10+
nodeExternalsPlugin({
11+
dependencies: false,
12+
}),
13+
],
14+
external: ['cors', 'kcors'],
15+
})
16+
.catch(err => {
17+
console.log(err)
18+
process.exit(1)
19+
})

build.sh

-7
This file was deleted.

configs/constants/envs.ts

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
export enum ENVS {
2+
DEVELOPMENT = 'DEVELOPMENT',
3+
STAGING = 'STAGING',
4+
PRODUCTION = 'PRODUCTION',
5+
}

configs/constants/index.ts

+21-30
Original file line numberDiff line numberDiff line change
@@ -2,48 +2,34 @@ import { bootstrapBefore } from '../bootstrap'
22
import development, { EevRecord } from './development'
33
import staging from './staging'
44
import production from './production'
5+
import { ENVS } from './envs'
56

67
const parsedEnvs = bootstrapBefore()
78

8-
export type Envs = {
9-
DEVELOPMENT: boolean
10-
STAGING: boolean
11-
PRODUCTION: boolean
12-
}
13-
14-
const getCurrentEnv = (): Envs => {
9+
const getCurrentEnv = (): ENVS => {
1510
const env = process.env?.ENV
16-
const up = `${env}`.toUpperCase()
17-
const currentEnvs: Envs = {
18-
DEVELOPMENT: false,
19-
STAGING: false,
20-
PRODUCTION: false,
21-
}
22-
if (up === 'PRODUCTION')
23-
return {
24-
...currentEnvs,
25-
PRODUCTION: true,
26-
}
27-
if (up === 'STAGING')
28-
return {
29-
...currentEnvs,
30-
STAGING: true,
31-
}
32-
return {
33-
...currentEnvs,
34-
DEVELOPMENT: true,
11+
if (typeof env === 'undefined') {
12+
console.warn(`/n> ENV is not set, fallback to ${ENVS.DEVELOPMENT}.`)
3513
}
14+
const upperCaseEnv = `${env}`.toUpperCase()
15+
if (upperCaseEnv === ENVS.PRODUCTION) return ENVS.PRODUCTION
16+
if (upperCaseEnv === ENVS.STAGING) return ENVS.STAGING
17+
return ENVS.DEVELOPMENT
3618
}
3719

38-
export type CurrentConstants = EevRecord
39-
40-
const getCurrentConstants = (envs: Envs): EevRecord => {
20+
const getCurrentConstants = (ident: ENVS): EevRecord => {
4121
let constants = development
42-
const source = envs.PRODUCTION ? production : envs.STAGING ? staging : development
22+
const source =
23+
ident === ENVS.PRODUCTION
24+
? production
25+
: ident === ENVS.STAGING
26+
? staging
27+
: development
4328
Object.keys(development).forEach(key => {
4429
const sourceValue = source[key]
4530
const processValue = process.env[key]
4631
const parsedValue = parsedEnvs[key]
32+
4733
if (typeof sourceValue !== 'undefined') {
4834
constants[key] = sourceValue
4935
}
@@ -55,9 +41,14 @@ const getCurrentConstants = (envs: Envs): EevRecord => {
5541
}
5642
})
5743

44+
constants.ENV_LABEL = source.ENV_LABEL
45+
5846
return constants
5947
}
6048

6149
export const CURRENT_ENV = getCurrentEnv()
50+
51+
export const isProd = () => CURRENT_ENV === ENVS.PRODUCTION
6252
const CONSTANTS = getCurrentConstants(CURRENT_ENV)
53+
6354
export default CONSTANTS

configs/koa.middlewares.ts

+4-2
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
import Koa from 'koa'
22
import logger from 'koa-logger'
33
import bodyParser from 'koa-bodyparser'
4-
import Environment from './constants'
4+
import { isProd } from './constants'
55

66
export const useMiddlewares = <T extends Koa>(app: T): T => {
7-
Environment.ENV_LABEL === 'PRODUCTION' && app.use(logger())
7+
if (isProd()) {
8+
app.use(logger())
9+
}
810

911
app.use(bodyParser())
1012

package.json

+7-8
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,12 @@
55
"description": "The best practice of building Koa2 with TypeScript",
66
"main": "app.ts",
77
"scripts": {
8-
"dev": "export NODE_ENV=development; nodemon --config nodemon.json",
8+
"dev": "export NODE_ENV=development; ts-node-dev -r tsconfig-paths/register app.ts",
99
"dev:db": "docker compose -f docker-compose.yml up -d",
1010
"prettier": "prettier --write '**/*.{js,ts}'",
1111
"test": "jest --config .jest.config.js --no-cache --detectOpenHandles",
12-
"prod:build": "bash ./build.sh",
13-
"prod:start": "prisma generate && prisma migrate deploy && export NODE_ENV=production; node ./releases/app.js"
12+
"prod:build": "node ./build.js",
13+
"prod:start": "prisma generate && prisma migrate deploy && export NODE_ENV=production; node ./dist/index.js"
1414
},
1515
"author": "unix (unix.bio@gmail.com)",
1616
"bugs": {
@@ -27,17 +27,16 @@
2727
"@types/koa": "^2.13.4",
2828
"@types/koa-bodyparser": "^4.3.5",
2929
"@types/node": "^17.0.8",
30+
"esbuild": "^0.14.11",
31+
"esbuild-node-externals": "^1.4.1",
3032
"jest": "^26.6.3",
31-
"nodemon": "^2.0.15",
3233
"prettier": "^2.5.1",
3334
"prisma": "^3.8.1",
3435
"supertest": "^4.0.2",
3536
"ts-jest": "^26.5.3",
36-
"ts-node": "^10.4.0",
37+
"ts-node-dev": "^1.1.8",
3738
"tsconfig-paths": "^3.12.0",
38-
"ttypescript": "^1.5.13",
39-
"typescript": "^4.5.4",
40-
"typescript-transform-paths": "^3.3.1"
39+
"typescript": "^4.5.4"
4140
},
4241
"dependencies": {
4342
"@prisma/client": "^3.8.1",

tsconfig.json

+3-6
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@
33
"allowJs": true,
44
"moduleResolution": "Node",
55
"module": "commonjs",
6-
"outDir": "./releases",
6+
"outDir": "./dist",
77
"lib": ["ESNext"],
88
"removeComments": true,
9+
"skipLibCheck": true,
910
"noImplicitAny": false,
1011
"esModuleInterop": true,
1112
"preserveConstEnums": true,
@@ -17,12 +18,9 @@
1718
],
1819
"baseUrl": ".",
1920
"paths": {
20-
"configs": ["configs"],
21+
"configs/*": ["./configs/*"],
2122
"app": ["app"]
2223
},
23-
"plugins": [
24-
{ "transform": "typescript-transform-paths" }
25-
]
2624
},
2725
"compileOnSave": false,
2826
"includes": [
@@ -33,7 +31,6 @@
3331
],
3432
"files": [
3533
"app.ts",
36-
"configs/connection.ts"
3734
],
3835
"exclude": [
3936
"node_modules",

0 commit comments

Comments
 (0)