源码地址:https://github.com/xuhow/ts-express-boilerplate
开发环境:macOS
1.新建ts-express-boilerplate目录
1 2 | mkdir ts-express-boilerplate cd ts-express-boilerplate |
2.初始化node
1 2 | # 在当前目录创建package.json文件 npm init -y # '-y'使用缺省配置 |
3.初始化TypeScript
1 2 3 4 5 | # 安装typescript npm install -D typescript # 创建tsconfig.json配置文件 npx tsc --init --rootDir ./src --outDir ./dist --sourceMap true |
4.创建node服务器
4.1 安装express依赖
1 2 | npm install express npm install -D @types/express |
4.2 创建express应用
新建src/index.ts,并编写如下代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import express, { Request, Response } from 'express'; const app = express(); const { PORT = 3000, } = process.env; app.get('/', (req: Request, res: Response) => { res.send({ message: 'hello, world', }); }); if (require.main === module) { app.listen(PORT, () => { console.log(`server started at http://localhost:${PORT}`); }); } export default app; |
此时,如果执行命令
5.配置webpack
5.1 安装webpack依赖
首先删除dist目录,然后安装webpack依赖
1 2 3 | rm -rf dist npm install -D webpack webpack-cli ts-loader touch webpack.config.js |
5.2 基本webpack.config.js配置
新建webpack.config.js配置文件并打开,然后编写如下代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | const path = require('path'); const { NODE_ENV = 'production', } = process.env; module.exports = { mode: NODE_ENV, target: 'node', entry: './src/index.ts', output: { path: path.resolve(__dirname, 'dist'), filename: 'index.js', }, resolve: { extensions: ['.ts', '.js'], }, module: { rules: [ { test: /\.ts$/, use: [ 'ts-loader', ], }, ] } } |
上述代码是最基本的webpack配置,编写完成后执行
5.3 不打包依赖包配置
1.安装webpack-node-externals
1 | npm install -D webpack-node-externals |
2.添加如下代码到webpack.config.js,然后执行
1 2 3 4 5 6 7 8 9 10 11 12 | ... const nodeExternals = require('webpack-node-externals'); ... module.exports = { ... externals: [ nodeExternals() ], } |
5.4 自动监测更改
当webpack.config.js的watch配置为
1 2 3 4 5 6 7 8 | ... module.exports = { ... watch: NODE_ENV === 'development', } |
5.5 自动重启node服务器
有了自动打包代码还不够,我们需要在webpack打包完成后自动重启node服务器。我们可以借助
1.安装nodemon-webpack-plugin
1 | npm install -D nodemon-webpack-plugin |
2.配置webpack.config.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | ... const NodemonPlugin = require('nodemon-webpack-plugin'); ... module.exports = { ... plugins: [ new NodemonPlugin(), ], } |
3.配置package.json
执行
最后,我们可以将
1 2 3 4 5 6 7 8 9 10 11 12 13 | { ... "scripts": { "start": "NODE_ENV=development webpack", ... }, ... } |
6.TODO
- 单元测试