Express + ts
- 搭建一个 nodejs + express + ts + 热加载的项目
npm init -y
- 安装依赖:
安装 express 和 typescript 作为项目的依赖
npm i express typescirpt -S
npm i @types/express @types/node --dev -D
- 配置 TypeScript
创建 tsconfig.json 文件,并配置以下内容:
也可以快速度创建 tsconfig.json 文件,并使用以下内容: npx tsc --init
{
"compilerOptions": {
"target": "es6", // 表示编译后的代码要兼容 es6 语法
"module": "commonjs", // 表示模块化方式为 commonjs
"strict": true, // 开启严格模式
"esModuleInterop": true, // 允许使用 import 语句
"skipLibCheck": true, // 跳过类型检查
"forceConsistentCasingInFileNames": true, // 文件名大小写敏感
"outDir": "./dist", // 编译后的代码输出目录
"rootDir": "./src", // 编译前的源代码目录
"resolveJsonModule": true // 允许导入 json 文件
},
"include": ["src/"], // 编译范围
"exclude": ["node_modules", "dist"] // 排除不需要编译的文件
}
- 创建 src 目录,并在其中创建 app.ts 文件,作为项目的入口文件
import express from 'express';
const app = express();
app.listen(3000, () => {
console.log('服务器端口已启动,请访问 http://localhost:3000')
});
- 在 package.json 文件中添加以下内容:
"scripts": {
"build": "tsc -W",
"test": "echo \"Error: no test specified\" && exit 1",
"start": "tsc && node dist/main.js",
"dev": "nodemon -w src -e ts,js --exec \"tsc && node dist/main.js\""
},
- 运行 npm run build 命令,启动项目,并在 dist 目录下生成编译后的代码。
- 运行 npm start 命令,启动项目,项目会编译 src 目录下的文件,并在 dist 目录下生成编译后的代码
- 运行 npm run dev 命令,启动项目
配置静态资源
- express 提供了一个静态资源方法
- 创建一个静态文件夹 public 文件夹
- 在router 中创建
views,ts
文件 ,然后进行导出
import express,{Router} from 'express';
const router:Router = express.Router();
import fs from 'fs';
router.get('/index.html',(req,res)=>{
fs.readFile('./views/index.html', 'utf8', (err,data)=>{
if(err) return res.status(500).send('服务器内部错误');
res.setHeader('Content-Type','text/html');
res.send(data);
})
})
export default router;
- 然后在
src
中创建 view 文件夹 创建 index.html
- 然后在 main.ts 中
app.use('/public', express.static('./public'))