nodejs typescript express mongodb 搭建简易服务器

郑宏朗
2023-12-01

安装依赖

npm i express mongoose ts-node typescript nodemon @types/express @types/node express-session @types/express-session

新建 tsconfig.json

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "outDir": "./lib",
        "strict": true,
        "esModuleInterop": true,
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true
    }
}

新建 nodemon.json

{
    "restartable": "rs",
    "ignore": [".git", "node_modules/", "dist/", "coverage/"],
    "watch": ["src/"],
    "execMap": {
        "ts": "ts-node --files"
    },
    "env": {
        "NODE_ENV": "development"
    },
    "ext": "js,json,ts"
}

修改 package.json

    "scripts": {
        "start": "node lib/app.js",
        "dev": "nodemon --config nodemon.json src/app.ts"
    },

新建 src/app.ts

import express from "express";
import path from "path";
import { controller } from "./controller";
import mongoose from "mongoose";
/** 链接数据库 */
mongoose.connect("mongodb://127.0.0.1/xxx");

const app = express();
/** 解析 post 数据 */
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
/** 静态资源 */
app.use(express.static(path.join(__dirname, "../public")));

app.listen(3022, () => {
    console.log("服务器启动, http://localhost:3000");
    // 控制器
    controller(app);
});

新建 src/models.ts

import { Schema, model } from "mongoose";

export interface User {
    /** 名字 */
    name: string;
    age: number
}

const schema = new Schema<User>({
    name: { type: String, required: true, unique: true },
    age: { type: Number, required: true },
});
schema.index({ name: 1 });
export const UserModel = model<User>("User", schema);

新建 src/controller.ts

import { Application } from "express";
 
export function controller(app: Application) {
    app.get("/test", (req, res) => {
        res.send(json("测试", "成功"));
    });
}

export function json(data?: any, message?: string) {
    return {
        code: !!data === true ? 1 : 0,
        data,
        message,
    };
}

启动项目

npm run dev

打包项目

tsc

运行打包项目

npm run start

拓展

使用 ejs 引擎作为前端渲染引擎

npm i ejs
app.set("views", path.join(__dirname, "./views")); //设置模版路径在views目录(默认)
app.set("view engine", "ejs"); //模版引擎设置为 ejs

添加 gulp 打包项目

npm i gulp

添加指令

{
	"build": "tsc && gulp"
}

添加 gulpfile.js 文件

const { src, dest, series } = require("gulp");
 
function views() {
    return src("./src/views/**/*").pipe(dest("./lib/views/"));
}

exports.default = series(views);
 类似资料: