statics.js 2.12 KB
const _ = require('lodash');
const config = global.yoho.config;

module.exports = (app) => {
    let manifest;

    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);
    }

    function getStatic(path, def) {
        return _.get(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 {data} = params;
                const {module: moduleName, page, localCss, isFeature, vue} = Object.assign({}, res.locals, data);

                if (moduleName && page) {
                    const statics = {
                        name: `${moduleName}.${page}`,
                        styles: [],
                        javascripts: [
                            getStatic('common.vendors.js', 'js/vendors.js'),
                            getStatic('common.main.js', 'js/main.js'),
                        ]
                    };

                    if (isFeature || localCss || vue) {
                        if (!isFeature) {
                            statics.styles.push(getStatic('common.main.css', 'css/main.css'));
                        }
                        statics.styles.push(
                            getStatic(`pages.${moduleName}.${page}.css`, `css/page.${moduleName}.${page}.css`));
                    } else {
                        statics.styles.push(getStatic('common.index.css', 'css/index.css'));
                    }

                    res.locals.statics = statics;
                    res.locals.preloads = _.concat(getPreloads(statics.styles, 'style'),
                        getPreloads(statics.javascripts, 'script', true));
                }
            }
        });
        return next();
    };
};