-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathssr.js
90 lines (78 loc) · 2.52 KB
/
ssr.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
const static = require('serve-static');
const { resolve, join, relative } = require('path');
const { pathExistsSync, readFileSync } = require('fs-extra');
const { resolve: resolveConfig } = require('./lib/config');
const {
csrBuildFileName,
ssrBuildFileName,
csrBuildDir,
ssrBuildDir,
css,
} = resolveConfig();
const cachesHtml = {};
function getScript(path) {
const script = require(path);
return script.default || script;
}
module.exports = function init({
dev,
templatePath,
ssrAppPath,
publicUrl,
templateKeys,
cacheHtml,
buildTimeout,
} = {}) {
templatePath = resolve(templatePath || join(__dirname, 'template.html'));
ssrAppPath = relative(
__dirname,
ssrAppPath || join(ssrBuildDir, ssrBuildFileName)
);
publicUrl = publicUrl || '/';
templateKeys = templateKeys || {
styles: /{{styles}}/g,
publicUrl: /{{publicUrl}}/g,
content: /{{content}}/g,
scripts: /{{scripts}}/g,
};
cacheHtml = cacheHtml === undefined ? true : cacheHtml;
// The default of buildTimeout is 5 Minutes
buildTimeout = buildTimeout === undefined ? 300000 : buildTimeout;
if (!pathExistsSync(templatePath))
throw new Error(`Cannot find HTML file with path "${templatePath}".`);
let timeoutExceeded;
let template;
let script;
const serveStatic = static(resolve(csrBuildDir));
const styleTags = `<link rel="stylesheet" href="${publicUrl}${css.buildFileName}" />`;
const scriptTags = `<script src="${publicUrl}${csrBuildFileName}"></script>`;
return {
serveBuildDir: (req, res, next) => serveStatic(req, res, next),
renderToString: function ({ url }) {
// Reload static assets
if (dev === undefined || dev || !template || !script) {
if (!pathExistsSync(resolve(__dirname, ssrAppPath))) {
if (timeoutExceeded) {
return `Can't find SSR Script in "${ssrAppPath}".`;
}
setTimeout(() => {
timeoutExceeded = true;
}, buildTimeout);
return 'Still building. Please refresh back later.';
}
template = readFileSync(templatePath, 'utf-8');
script = getScript(ssrAppPath);
}
let html = cachesHtml[url];
if (!cacheHtml || !html) {
html = template
.replace(templateKeys.publicUrl, publicUrl)
.replace(templateKeys.styles, styleTags)
.replace(templateKeys.scripts, scriptTags)
.replace(templateKeys.content, script.render({ url }).html);
if (cacheHtml) cachesHtml[url] = html;
}
return html;
},
};
};