1.首先需要构建package.json文件:
执行命令:npm init
进行初始化
修改package.json如下:
{
"name": "js_server",
"version": "1.0.0",
"description": "a server use js to run",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
},
"author": "",
"license": "ISC",
"devDependencies": {
"@types/koa": "^2.0.46",
"@types/koa-router": "^7.0.31",
"nodemon": "^1.18.4",
"ts-node": "^7.0.1",
"typescript": "^3.0.3"
}
}
2.安装typescript以及其依赖库:
npm i koa koa-router
npm i --save-dev typescript ts-node nodemon // nodemon主要用于热加载APP
npm i --save-dev @types/koa @types/koa-router
3.构建tsconfig.json
此时的项目结构:
项目结构.png
{
"compilerOptions": {
"module": "commonjs",
"target": "es2017",
"noImplicitAny": true,
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist", // TS文件编译后会放入到此文件夹内
"baseUrl": ".",
"paths": {
"*": [
"node_modules/*", //根据项目的路径指定
"src/types/*" //根据项目的路径指定
]
}
},
"include": [
"src/**/*" //根据项目的路径指定
]
}
4.构建hello world 的APP
import * as Koa from 'koa'
import * as Router from 'koa-router'
const app = new Koa();
const router = new Router();
router.get('/*',async(ctx) => {
ctx.body = "Hellow World !";
})
app.use(router.routes());
app.listen(3000);
console.log('Server is runing !!')
5.配置热加载
需要在packge.json配置中修改scripts如下:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "tsc && node dist/app.js",
"watch-server":"nodemon --watch ./src/app.ts -e ts,tsx --exec ts-node ./src/app.ts"
},
6.运行APP
npm run watch-server
网友评论