koa3-cli 1.0.8 → 1.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/app/setup.js +34 -2
- package/package.json +1 -1
package/app/setup.js
CHANGED
|
@@ -16,12 +16,44 @@ const router = require('./router');
|
|
|
16
16
|
|
|
17
17
|
const rootDir = path.join(__dirname, '..');
|
|
18
18
|
|
|
19
|
+
/**
|
|
20
|
+
* 生成静态资源缓存配置。
|
|
21
|
+
*
|
|
22
|
+
* SPA 的入口 index.html 会引用最新一批带 hash 的 JS/CSS 文件,如果入口文件被浏览器或 CDN
|
|
23
|
+
* 长时间缓存,用户发布后仍会拿到旧入口,进而继续加载旧资源。这里仅禁止 index.html 缓存,
|
|
24
|
+
* 其他静态资源继续使用配置里的 maxAge,保证发布更新及时生效且不影响资源缓存性能。
|
|
25
|
+
*
|
|
26
|
+
* @param {Object} staticOptions koa-static 原始配置项
|
|
27
|
+
* @returns {Object} 注入 index.html 不缓存策略后的 koa-static 配置项
|
|
28
|
+
*/
|
|
29
|
+
function createStaticOptions(staticOptions = {}) {
|
|
30
|
+
const userSetHeaders = staticOptions.setHeaders;
|
|
31
|
+
|
|
32
|
+
return {
|
|
33
|
+
...staticOptions,
|
|
34
|
+
setHeaders(res, filePath, stats) {
|
|
35
|
+
if (typeof userSetHeaders === 'function') {
|
|
36
|
+
userSetHeaders(res, filePath, stats);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// koa-send 在启用 gzip/brotli 时传入的是 index.html.gz / index.html.br,
|
|
40
|
+
// 需要去掉压缩扩展名后再判断,避免预压缩入口文件继续被长缓存。
|
|
41
|
+
const normalizedFileName = path.basename(filePath).replace(/\.(br|gz)$/i, '');
|
|
42
|
+
if (normalizedFileName === 'index.html') {
|
|
43
|
+
res.setHeader('Cache-Control', INDEX_HTML_CACHE_CONTROL);
|
|
44
|
+
res.setHeader('Pragma', 'no-cache');
|
|
45
|
+
res.setHeader('Expires', '0');
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
19
51
|
function setup(app, config, logger) {
|
|
20
52
|
// 静态资源
|
|
21
53
|
if (config.static && config.static.enable !== false) {
|
|
22
54
|
const staticPath = path.join(rootDir, config.static.dir || 'public');
|
|
23
|
-
if (fs.existsSync(staticPath)) {
|
|
24
|
-
app.use(serveStatic(staticPath, config.static.options || {}));
|
|
55
|
+
if (fs.existsSync(staticPath)) {
|
|
56
|
+
app.use(serveStatic(staticPath, createStaticOptions(config.static.options || {})));
|
|
25
57
|
}
|
|
26
58
|
}
|
|
27
59
|
|