Skip to content
This repository was archived by the owner on May 19, 2025. It is now read-only.

Commit 481048f

Browse files
committed
🐛 Fixing index html has long term cache
- When STATIC_PREFIX is empty, which means static assets are in root path
1 parent 2132c1f commit 481048f

File tree

2 files changed

+30
-12
lines changed

2 files changed

+30
-12
lines changed

app.js

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ const DEV_MODE = config.isDevMode();
2525
const DEFAULT_PREFIX_KEY = 'defaultPrefix';
2626
const API_ENDPOINTS = config.getApiEndPoints();
2727
const isHMREnabled = config.isHMREnabled();
28+
const servingStaticIndex = config.isServingStaticIndex();
2829

2930
function initAppCommon() {
3031
const app = new Koa();
@@ -48,28 +49,42 @@ function initApp(app) {
4849
app.use(favicon(path.join(__dirname, 'build/app/favicon.ico')));
4950

5051
// =====serve static=====
51-
let staticPrefix = path.join(
52-
config.getAppPrefix(),
53-
config.getStaticPrefix() || '/'
54-
);
52+
const ROOT_PATH = '/';
53+
let staticPrefixConfig = config.getStaticPrefix();
54+
let staticPrefix = path.join(config.getAppPrefix(), staticPrefixConfig);
55+
if (!staticPrefix.startsWith(ROOT_PATH)) {
56+
staticPrefix = ROOT_PATH;
57+
}
5558

5659
if (sysUtils.isWindows()) {
5760
staticPrefix = sysUtils.replaceBackwardSlash(staticPrefix);
5861
}
59-
// app.use(mount(staticPrefix, conditional()));
60-
// app.use(mount(staticPrefix, etag()));
62+
63+
const staticOptions = {
64+
// one month cache for prod
65+
maxage: DEV_MODE ? 0 : 2592000000,
66+
gzip: false,
67+
setHeaders(res, path) {
68+
if (path.endsWith('.html')) {
69+
res.setHeader('Cache-Control', 'no-cache');
70+
}
71+
},
72+
};
73+
const isStaticAssetsInRoot =
74+
!staticPrefixConfig || staticPrefixConfig == ROOT_PATH;
75+
if (isStaticAssetsInRoot && !servingStaticIndex) {
76+
//workaround: use a random index to pass through the static middleware
77+
staticOptions.index = `${Math.random().toString()}.html`;
78+
}
79+
6180
app.use(
6281
mount(
6382
staticPrefix,
64-
serveStatic(path.join(__dirname, 'build/app'), {
65-
// one month cache for prod
66-
maxage: DEV_MODE ? 0 : 2592000000,
67-
gzip: false,
68-
})
83+
serveStatic(path.join(__dirname, 'build/app'), staticOptions)
6984
)
7085
);
7186
// handle static not found, do not pass further down
72-
if (staticPrefix && staticPrefix != '/') {
87+
if (!isStaticAssetsInRoot) {
7388
app.use(
7489
mount(staticPrefix, ctx => {
7590
ctx.status = 404;

config/env.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,9 @@ module.exports = {
181181
getHMRPort: () => {
182182
return getConfigProperty('HMR_PORT');
183183
},
184+
isServingStaticIndex: () => {
185+
return isTrue(getConfigProperty('SERVE_STATIC_INDEX'));
186+
},
184187
getEnv: key => {
185188
return getConfigProperty(key);
186189
},

0 commit comments

Comments
 (0)