背景
限制 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 时的解析即可。
- 本文作者: Dongsj
- 本文链接: blog.dongsj.cn/20180504-ex…
- 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!