UNPKG

2.55 kBJavaScriptView Raw
1const fs = require('fs-extra');
2const path = require('path');
3
4const getCwd = require('../utils/get-cwd');
5
6// const { version } = require('../package.json')
7
8/**
9 * 处理模板内容代码并返回最终结果
10 * @param {String} optionTemplate 模板文件路径或模板内容代码
11 * @returns {String} 处理后的模板内容代码
12 */
13const validateTemplate = optionTemplate => {
14 if (typeof optionTemplate !== 'string')
15 throw new Error('validate-template: `template` need to be String');
16
17 let template;
18 if (fs.existsSync(optionTemplate)) {
19 template = fs.readFileSync(optionTemplate, 'utf-8');
20 } else if (optionTemplate.substr(0, 2) === './') {
21 template = fs.readFileSync(
22 path.resolve(getCwd(), optionTemplate),
23 'utf-8'
24 );
25 } else if (path.isAbsolute(optionTemplate)) {
26 template = fs.readFileSync(path.resolve(optionTemplate), 'utf-8');
27 }
28
29 {
30 // 检查关键 inject 是否存在
31 const important = {
32 head: {
33 append: ['metas', 'styles']
34 },
35 body: {
36 prepend: ['react'],
37 append: ['scripts']
38 }
39 };
40
41 Object.keys(important).forEach(tagName => {
42 Object.keys(important[tagName]).forEach(type => {
43 important[tagName][type].forEach(inject => {
44 const regex = new RegExp(`<%\\W*inject\\.${inject}\\W*%>`);
45
46 // 存在该注入,跳过
47 if (regex.test(template)) return;
48
49 const str = (() => {
50 if (inject === 'react')
51 return `<div id="root"><%- inject.${inject} %></div>`;
52 return `<%- inject.${inject} %>`;
53 })();
54 template = template.replace(
55 new RegExp(
56 `<${type == 'append' ? '/' : ''}${tagName}.*?>`
57 ),
58 match => {
59 if (type === 'prepend') return `${match}\n${str}`;
60 return `${str}\n${match}`;
61 }
62 );
63 });
64 });
65 });
66 }
67
68 // console.log({ template })
69
70 return (
71 template +
72 `\n<!-- rendered by using koot.js ${process.env.KOOT_VERSION} -->`
73 );
74};
75
76module.exports = validateTemplate;