forked from brunch/handlebars-brunch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
81 lines (66 loc) · 2.27 KB
/
index.js
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
'use strict';
const handlebars = require('handlebars');
const umd = require('umd-wrapper');
const sysPath = require('path');
class HandlebarsCompiler {
constructor(cfg) {
this.optimize = cfg.optimize;
const config = cfg.plugins.handlebars || {};
const overrides = config.overrides;
if (typeof overrides === 'function') overrides(handlebars);
const ns = config.namespace;
this.namespace = typeof ns === 'function' ? ns : () => ns;
this.pathReplace = config.pathReplace || /^.*templates\//;
this.includeSettings = config.include || {};
this.locals = config.locals || {};
}
get include() {
let includeFile = 'handlebars';
const include = this.includeSettings;
if (include.runtime !== false) includeFile += '.runtime';
if (include.amd) includeFile += '.amd';
if (this.optimize) includeFile += '.min';
includeFile += '.js';
return [
sysPath.join(__dirname, 'dist', includeFile),
sysPath.join(__dirname, 'ns.js'),
];
}
compile(file) {
const path = file.path;
let data = file.data;
if (this.optimize) {
data = data.replace(/^[\x20\t]+/mg, '').replace(/[\x20\t]+$/mg, '');
data = data.replace(/^[\r\n]+/, '').replace(/[\r\n]*$/, '');
}
try {
let result;
const ns = this.namespace(path);
const source = `Handlebars.template(${handlebars.precompile(data)})`;
if (ns) {
// eslint-disable-next-line prefer-template
const key = ns + '.' + path.replace(/\\/g, '/').replace(this.pathReplace, '').replace(/\..+?$/, '').replace(/\//g, '.');
result = `Handlebars.initNS( '${key}' ); ${key} = ${source}`;
} else {
result = umd(source);
}
return Promise.resolve(result);
} catch (error) {
return Promise.reject(error);
}
}
compileStatic(file) {
try {
const template = handlebars.compile(file.data);
const source = template(this.locals);
return Promise.resolve(source);
} catch (error) {
return Promise.reject(error);
}
}
}
HandlebarsCompiler.prototype.brunchPlugin = true;
HandlebarsCompiler.prototype.type = 'template';
HandlebarsCompiler.prototype.pattern = /\.(hbs|handlebars)$/;
HandlebarsCompiler.prototype.staticTargetExtension = 'html';
module.exports = HandlebarsCompiler;