本教程我们实现一个山寨reddit网站 项目目录名为lireddit
首先编写服务端 ,创建服务端目录 lireddit-server ,初始化项目 安装@types/node ts-node typescript等
mkdir lireddit
cd lireddit
mkdir lireddit-server
cd lireddit-server
npm init -y
npm i yarn -g
yarn add -D @types/node ts-node typescript
配置package.json的启动命令 start为
"scripts": {
"start":"ts-node src/index.ts"
}
创建文件 src/index.ts
然后运行命令npx tsconfig.json
npx tsconfig.json
选择y ,选择node
自动创建好的tsconfig.json长这样:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"lib": [
"dom",
"es6",
"es2017",
"esnext.asynciterable"
],
"sourceMap": true,
"outDir": "./dist",
"moduleResolution": "node",
"removeComments": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"noImplicitThis": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"resolveJsonModule": true,
"baseUrl": "."
},
"exclude": [
"node_modules"
],
"include": [
"./src/**/*.tsx",
"./src/**/*.ts"
]
}
现在测试yarn start命令是否ok,首先在src/index.ts中添加内容
console.log('hello world');
然后在lireddit-server目录下运行命令
yarn start
运行成功
在package.json中再加入watch命令
"scripts": {
"watch":"tsc -w",
"start": "ts-node src/index.ts"
},
运行命令 yarn watch
yarn watch
src文件夹下的所有ts文件都会被监控,有任何改动会进行重新编译生成文件到到dist文件夹中
修改package.json中的start命令 ,使用node运行dist文件中的js文件
"scripts": {
"watch":"tsc -w",
"start":"node dist/index.js",
"start2": "ts-node src/index.ts"
},
重新开启终端 运行yarn start测试是否work
yarn start
安装nodemon
yarn add -D nodemon
在package.json中添加dev命令
"scripts": {
"watch":"tsc -w",
"dev":"nodemon dist/index.js",
"start":"node dist/index.js",
"start2": "ts-node src/index.ts"
},
nodemon也可以执行ts文件, 比如dev2的写法
"scripts": {
"watch": "tsc -w",
"dev": "nodemon dist/index.js",
"start": "node dist/index.js",
"start2": "ts-node src/index.ts",
"dev2":"nodemon --exec ts-node src/index.ts"
}
安装mikro-orm mikro-orm官网 https://mikro-orm.io/
yarn add @mikro-orm/cli @mikro-orm/core @mikro-orm/migrations @mikro-orm/postgresql pg
创建数据库lireddit,输入命令 createdb lireddit
createdb lireddit