# All files / src/Page PageVueServerRenderer.ts

28.57% Statements 10/35
100% Branches 0/0
0% Functions 0/7
29.41% Lines 10/34

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130

    1x
    1x
    1x
    1x
    1x
    1x

    1x

    1x

    1x

    1x

     /* eslint-disable import/no-import-module-exports */
    /*
      Note: the function `requireFromString` causes eslint to detect a false-positive
      due to the usage of `module`. Hence, the use of the above `eslint-disable`.
    */
    import Vue from 'vue';
    import path from 'path';
    import fs from 'fs-extra';
    import * as VueCompiler from 'vue-template-compiler';
    import { createRenderer } from 'vue-server-renderer';
    import * as logger from '../utils/logger';
    import type { PageConfig, PageAssets } from './PageConfig';
    import type { Page } from '.';
    /* eslint-enable import/no-import-module-exports */

    let bundle = require('@markbind/core-web/dist/js/vueCommonAppFactory.min');

    const { renderToString } = createRenderer();

    interface PageEntry {
      page: Page;
      compiledVuePage: VueCompiler.CompiledResultFunctions;
      pageNav: string;
    }

    // hold the mapping of sourcePath to latest built pages (for hot-reload dev purposes)
    const pageEntries: Record<string, PageEntry> = {};

    /**
     * Compiles page into Vue Application to get the page render function and places
     * it into a script so that the browser can retrieve the page render function to
     * render the page during Vue mounting.
     *
     * This is to avoid the overhead of compiling the page into Vue application
     * on the client's browser (alleviates FOUC). It is also the pre-requisite to enable SSR.
     *
     * @param content Page content to be compiled into Vue app
     */
    async function compileVuePageAndCreateScript(
      content: string, pageConfig: PageConfig, pageAsset: PageAssets):
      Promise<VueCompiler.CompiledResultFunctions> {
      // Compile Vue Page
      const compiledVuePage = VueCompiler.compileToFunctions(content);

      // Set up script content
      const outputContent = `
        var pageVueRenderFn = ${compiledVuePage.render};
        var pageVueStaticRenderFns = [${compiledVuePage.staticRenderFns}];
      `;

      // Get script file name
      const pageHtmlFileName = path.basename(pageConfig.resultPath, '.html');
      const scriptFileName = `${pageHtmlFileName}.page-vue-render.js`;

      /*
       * Add the script file path for this page's render function to the page's assets (to populate page.njk).
       * The script file path is the same as the page's file path.
       */
      pageAsset.pageVueRenderJs = scriptFileName;

      // Get script's absolute file path to output script file
      const dirName = path.dirname(pageConfig.resultPath);
      const filePath = path.join(dirName, scriptFileName);

      await fs.outputFile(filePath, outputContent);

      return compiledVuePage;
    }

    /**
     * Renders Vue page app into html string (Vue SSR).
     * This function will install the MarkBindVue plugin and render the built Vue page content into html string.
     */
    async function renderVuePage(compiledVuePage: VueCompiler.CompiledResultFunctions): Promise<string> {
      const { MarkBindVue, appFactory } = bundle;

      const { components, directives } = MarkBindVue;

      const VueAppPage = new Vue({
        render(createElement: any) {
          return compiledVuePage.render.apply(this, createElement);
        },
        staticRenderFns: compiledVuePage.staticRenderFns,
        components,
        directives,
        ...appFactory(),
      });

      return renderToString(VueAppPage);
    }

    /**
     * Referenced from stackOverflow:
     * https://stackoverflow.com/questions/17581830/load-node-js-module-from-string-in-memory
     *
     * Credits to Dominic
     */
    function requireFromString(src: string, filename: string) {
      const m = new (module.constructor as any)();
      m.paths = module.paths; // without this, we won't be able to require Vue in the string module
      m._compile(src, filename);
      return m.exports;
    }

    /**
     * Retrieves the latest updated MarkBindVue bundle from webpack compiler watcher,
     * re-render all the built pages, and output the page html files.
     * This function will only be used in development mode (for MarkBindVue bundle hot-reloading purposes).
     */
    async function updateMarkBindVueBundle(newBundle: string): Promise<void> {
      logger.info(`Changes detected in MarkBind Vue Source Files:
    Bundle is regenerated by webpack and built pages are re-rendered with the latest bundle.`);

      // reassign the latest updated MarkBindVue bundle
      bundle = requireFromString(newBundle, '');

      Object.values(pageEntries).forEach(async (pageEntry) => {
        const { page, compiledVuePage } = pageEntry;
        const renderedVuePageContent = await renderVuePage(compiledVuePage);
        page.outputPageHtml(renderedVuePageContent);
      });
    }

    export const pageVueServerRenderer = {
      compileVuePageAndCreateScript,
      renderVuePage,
      updateMarkBindVueBundle,
      pageEntries,
    };