44

一种 NodeJS 全栈项目的构架方式

 4 years ago
source link: https://www.tuicool.com/articles/fi63uyM
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在开发 NodeJS 中后台项目时,有很多情况下会遇到一种需要将服务端与客户端代码写在同一个项目中的情况(如自带管理后台的项目)。本文提供一种前后端代码合并的思路。

主要的思路是:在项目中给客户端单独分配一个目录,在目录中创建完整的 npm 项目,开发时同时启动客户端开发服务及后端服务,通过 http-proxy-middleware 将两个项目连接起来。

以下将以 express + vue 结合的项目为例做出说明。

项目目录结构如下:

--- client
  |-- dist
  |-- src
  |-- public
  |-- vue.config.js
  |-- package.json
--- routes
  |-- client.js
  |-- ...other.js
--- static
--- index.js
--- package.json

主项目的 npm scripts 如下:

"dev": "concurrently \"npm run serve\" \"npm run client\""
"serve": "node index",
"client": "cd client && npm run serve"

主要方法是通过 concurrently 同时启动两个 npm script

client 是一个通过 vue-cli 生成的 vue 项目,主要的 npm scripts 如下:

"serve": "vue-cli-service serve"

配置好主项目的 scripts 后,接下来在 express 客户端相关的路由 routes/client.js 中添加判断环境的相关逻辑,配合 http-proxy-middleware 转发请求至 vue 开发服务器

const express = require('express')
const router = express.Router()

const isProduction = process.env.NODE_ENV === 'production'

// 可在这里添加其他接口,如管理后台可能会用到的数据接口

if (isProduction) {
  // 上线时需要构建 client 项目至 dist 目录中
  router.use(express.static('./client/dist'))
  router.use('*', express.static('./client/dist/index.html'))
} else {
  // 假设 vue dev server 监听的端口为 30000
  router.use(require('http-proxy-middleware')('http://localhost:30000'))
}

通过以上的设置,使用 npm run dev 即可非常容易地进行开发。

这种方式有以下几个优点:

  • 前后端代码在同一项目中,便于前后端关联的功能修改
  • 不使用 webpack-dev-middleware ,使用 vue-cli 提供的配置,无需单独的 webpack 配置文件
  • 开发及生产环境皆不需要配置跨域
  • 生产环境客户端为纯静态文件,利于缓存

不过这种结构仅适用于前后端项目规模都不大,或是单人开发的项目,其他情况还是建议直接分离前后端项目。

本文没有提到的部署,可通过 husky 配置 pre-commit 脚本进行本地构建后提交或适用 CI 来进行客户端的构建,这里就不详细展开了。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK