statics.js
2.91 KB
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
const _ = require('lodash');
const config = global.yoho.config;
module.exports = (app) => {
let manifest,
manifestQcdn;
let assetUrl = config.assetUrl,
assetUrlQcdn = assetUrl.replace(/\/\/cdn.yoho.cn/gi, '//qcdn.yoho.cn');
if (!app.locals.devEnv) {
let manifestPath = '../../manifest.json';
if (app.locals.isTest) {
manifestPath = `../../dist/statics/${config.appName}/${app.locals.version}/manifest.json`;
}
manifest = require(manifestPath);
}
if (manifest) {
try {
let strManifest = JSON.stringify(manifest);
strManifest = strManifest.replace(/\/\/cdn.yoho.cn/gi, '//qcdn.yoho.cn');
manifestQcdn = JSON.parse(strManifest);
} catch(e) { // eslint-disable-line
manifestQcdn = manifest;
}
}
function getStatic(path, def, qcdn) {
return _.get(qcdn ? manifestQcdn : manifest, path, `${config.assetUrl}${def}`);
}
function getPreloads(list, type, cross) {
let _list = [];
_.forEach(list, url => {
_list.push({url, type, cross});
});
return _list;
}
return (req, res, next) => {
res.on('beforeRender', (params) => {
if (params) {
const qcdn = _.get(req.app.locals, 'wap.qcloud_cdn');
const {data} = params;
const {module: moduleName, page, localCss, isFeature, vue} = Object.assign({}, res.locals, data);
const getStaticWithCdn = (path, def) => {
return getStatic(path, def, qcdn);
};
if (moduleName && page) {
const statics = {
name: `${moduleName}.${page}`,
styles: [],
javascripts: [
getStaticWithCdn('common.vendors.js', 'js/vendors.js'),
getStaticWithCdn('common.main.js', 'js/main.js'),
]
};
if (isFeature || localCss || vue) {
if (!isFeature) {
statics.styles.push(getStaticWithCdn('common.main.css', 'css/main.css'));
}
statics.styles.push(
getStaticWithCdn(`pages.${moduleName}.${page}.css`, `css/page.${moduleName}.${page}.css`));
} else {
statics.styles.push(getStaticWithCdn('common.index.css', 'css/index.css'));
}
res.locals.statics = statics;
res.locals.staticAssetUrl = qcdn ? assetUrlQcdn : assetUrl;
res.locals.preloads = _.concat(getPreloads(statics.styles, 'style'),
getPreloads(statics.javascripts, 'script', true));
}
}
});
return next();
};
};