yoho-pages-loader.js 1.67 KB
const shelljs = require('shelljs');
const _ = require('lodash');
const path = require('path');
const fs = require('fs');

module.exports = function(source) {
    let transforSource = '';
    const options = eval(source); //eslint-disable-line
    const pageTpl = fs.readFileSync(path.join(__dirname, './yoho-pages-template.tpl'), 'utf-8');

    //     transforSource += `
    // window.pageJsRoute = (name) => {
    //     switch (name) {
    //         case 'product.new-detail':
    //             return import(/* webpackChunkName: "page.product.new-detail" */ './js/product/new-detail.page.js')
    //         case 'common.offline':
    //             return import(/* webpackChunkName: "page.common.offline" */ './js/common/offline.page.js')
    //     }
    // }`;
    transforSource += _.join(_.map(options.regx, regx => {
        return _.join(_.map(shelljs.ls(path.join(this.context, options.context, regx)), file => {
            const dir = _.slice(file.split('/'), -3);
            let moduleName, pageName;

            if (_.last(dir) === 'index.js') { // [modulename, page, index.js]
                moduleName = _.nth(dir, 0);
                pageName = _.nth(dir, 1);
            } else { // [xxx, modulename, xx.page.js]
                moduleName = _.nth(dir, 1);
                pageName = _.nth(dir, 2).match(/(.*).page.js/)[1];
            }
            return `
        case '${moduleName}.${pageName}':
            return  import(/* webpackChunkName: "page.${moduleName}.${pageName}" */ './${path.relative(this.context, file)}');`; //eslint-disable-line
        }), '');
    }), '');

    transforSource = pageTpl.replace('##placeholder##', transforSource);

    return transforSource;
};