网站首页 > 博客文章 正文
koa2可以完全使用单文件开发服务器,但是我相信没有人会这样做,为了方便开发,我们需要调整项目结构,使项目目录清晰明朗,为后期扩展打下基础。
初始化项目结构
在根目录下创建 src 目录,用来存储我们的项目逻辑,在 src 目录下创建 router 目录,将路由处理放在下面
- src
- router
- index.ts
- app.ts
- main.ts
- README.md
初始化路由配置
// src/router/index.ts
import KoaRouter from 'koa-router';
const router = new KoaRouter();
export default router;
初始化 koa 服务
// src/app.ts
import Koa from 'koa';
import router from './router';
import { Server } from 'http';
// 创建服务对象
const app = new Koa();
// 引入路由
app.use(router.routes());
app.use(router.allowedMethods());
// 启动服务
const runServer = (port: number): Server => {
console.log('Server running on port 3000');
return app.listen(port);
};
export default runServer;
// src/main.ts
import runServer from './app';
runServer(3000);
配置服务启动命令
// package.json
{
...
"scripts": {
"start": "ts-node ./src/main.ts"
},
"dependencies": {
...
},
"devDependencies": {
...
}
}
服务热加载
安装 nodemon
yarn add -D nodemon
配置 nodemon
在根目录下增加 nodemon.json 文件
{
// 延迟重载
"delay": 1000,
// 监听的目录和文件
"watch": ["src/**/*.ts"],
// 忽略的目录
"ignore": ["node_modules"],
// 执行的命令
"exec": "ts-node ./src/main.ts",
// 监听的文件后缀
"ext": "ts"
}
配置环境变量读取
yarn add dotenv
yarn add -D @types/dotenv
加载环境变量
- 创建环境变量文件 .env
// .env
NODE_ENV=dev
SERVER_PORT=3300
- index.ts 中引入
// 在文件头部
import dotenv from 'dotenv';
dotenv.config();
- 创建配置文件 src/config/index.ts
const config = {
server: {
port: Number(process.env.SERVER_PORT) || 3300,
},
};
export default config;
使用环境变量
在 index.ts 中指定启动端口
import config from './src/config';
runServer(config.server.port);
- 上一篇: 揭秘微前端import-html-entry的强大之处
- 下一篇: 带你五步学会Vue SSR
猜你喜欢
- 2024-12-25 JMeter:断言之响应断言
- 2024-12-25 nginx作用及其配置
- 2024-12-25 动态主机配置协议——DHCP详解
- 2024-12-25 快速掌握和使用Flyway
- 2024-12-25 想了解Python源代码加密吗?现总结如下5大加密混淆手段!
- 2024-12-25 如何在MVC中将ActiveReports后台参数传递给前台
- 2024-12-25 Linux 学习笔记之简单的SSH远程连接配置
- 2024-12-25 Vue基础二——Vue-cli
- 2024-12-25 Zabbix 随笔:6.0 LTS 源码安装
- 2024-12-25 Spring Boot 项目部署方案!打包 + Shell 脚本部署详解,稳的一批
你 发表评论:
欢迎- 最近发表
-
- Python 中 必须掌握的 20 个核心函数—len()函数
- 用PLC的指针实现字符串转byte(Codesys平台)一文极简搞懂指针
- EXCEL如何用函数读取复杂字符串中的数据
- 2025-07-19:计算字符串的镜像分数。用go语言,给定一个字符串 s
- 2025-07-10:字符相同的最短子字符串Ⅰ。用go语言,给定一个长度
- 基于物理特征融合与机器学习的多井协同钻井速率实时预测与优化(
- [电子学报文章精选]一种基于特征融合的恶意代码快速检测方法
- 强大的可视化流程图编辑神器 — LogicFlow
- 前端框架太卷了!字节企业级框架Arco Design Mobile开源了
- Vue独立组件——11个最佳Vue.js日期选择器组件
- 标签列表
-
- ifneq (61)
- 字符串长度在线 (61)
- googlecloud (64)
- flutterrun (59)
- powershellfor (73)
- messagesource (71)
- plsql64位 (73)
- vueproxytable (64)
- npminstallsave (63)
- promise.race (63)
- 2019cad序列号和密钥激活码 (62)
- window.performance (66)
- qt删除文件夹 (72)
- mysqlcaching_sha2_password (64)
- nacos启动失败 (64)
- ssh-add (70)
- yarnnode (62)
- abstractqueuedsynchronizer (64)
- source~/.bashrc没有那个文件或目录 (65)
- springboot整合activiti工作流 (70)
- jmeter插件下载 (61)
- 抓包分析 (60)
- idea创建mavenweb项目 (65)
- qcombobox样式表 (68)
- pastemac (61)
本文暂时没有评论,来添加一个吧(●'◡'●)