File size: 1,278 Bytes
494c9e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2fdca4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
494c9e4
 
 
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
/**
 * 构建时展开 HTML 中的 <!-- INCLUDE path/to/partial.html -->(path 相对 client/src)。
 * 由 webpack CopyWebpackPlugin 的 transform 调用;源 HTML 仅保留占位符,不写入展开结果。
 */

const fs = require('fs');
const path = require('path');

/** 含行首空白,避免占位行缩进与 partial 首行缩进叠加 */
const INCLUDE_RE = /[ \t]*<!--\s*INCLUDE\s+(\S+)\s*-->/g;

/**
 * @param {string} html
 * @param {string} srcRoot 绝对路径,一般为 client/src
 * @returns {string}
 */
function expandHtmlIncludes(html, srcRoot) {
    let out = html;
    for (let pass = 0; pass < 32; pass++) {
        let changed = false;
        out = out.replace(INCLUDE_RE, (_match, relPath) => {
            changed = true;
            const full = path.resolve(srcRoot, relPath);
            if (!fs.existsSync(full)) {
                throw new Error(`includeHtmlPartials: missing file ${full} (INCLUDE ${relPath})`);
            }
            return fs.readFileSync(full, 'utf8');
        });
        if (!changed) break;
    }
    if (/[ \t]*<!--\s*INCLUDE\s+\S+\s*-->/.test(out)) {
        throw new Error('includeHtmlPartials: nested INCLUDE depth limit (possible cycle)');
    }
    return out;
}

module.exports = { expandHtmlIncludes };