背景
限制 SPA 应用已经成为主流, 在项目开发阶段产品经理和后端开发同学经常要查看前端页面, 下面就是我们团队常用的使用 express 搭建的 SPA 静态资源服务器方案.
为 SPA 应用添加入口 (index.html) 的 sendFile
当 SPA 应用开启 html5 mode 的情况下, 指定 url 下 (<base href="/"> 的情况为 /)的全部请求都会访问入口文件(一般情况下是 index.html), 然后 SPA 应用会根据 url 再去决定访问的实际页面.
所以我们需要为全部路径添加 sendFile 来发送 index.html 文件内的内容, 并将其缓存实际设为 0, 代码如下:
- app.use("/**", function (req, res) {
- res.sendfile(staticPath+"/index.html", {maxAge: 0});
- });
为 SPA 应用添加其他静态资源
由于 Express 中间件的特性, 在 index.html 的 sendFile 之前我们需要将其他静态资源进行处理, 具体代码如下:
- const options = process.env.env == 'prod' ? {maxAge: '3d'} : {maxAge: '1m'};
- app.use(express.static(path.join(__dirname, staticPath), options));
- });
SPA 静态资源服务器的全部代码
下面是 SPA 静态资源服务器 app.js 的全部代码:
- const express = require('express');
- const path = require('path');
- const http = require('http');
- const app = express();
- const staticPath=process.env.static ||'dist';
- const port=process.env.port || 3000;
- const options = process.env.env == 'prod' ? {maxAge: '3d'} : {maxAge: '1m'};
- app.use(express.static(path.join(__dirname, staticPath), options));
- app.use("/**", function (req, res) {
- res.sendfile(staticPath+"/index.html", {maxAge: 0});
- });
- const server = http.createServer(app);
- server.listen(port);
- console.log(`env:${process.env.env}`);
- console.log(`path:${staticPath}`);
- console.log(`port:${port}`);
执行以下命令即可指定 SPA 项目路径和端口号启动服务器了
export static=www&&export port=8101 && export env=prod && node ./app.js
结语
SPA 静态资源服务器的实现较为简单, 其实只需要理解了 Express 的中间件和 SPA 应用在使用 html5 mode 时的解析即可.
来源: http://www.qdfuns.com/article/20150/14a1560a493abd97850c3b04e868a50c.html