-
Notifications
You must be signed in to change notification settings - Fork 1
/
gulp-html-compile.js
54 lines (39 loc) · 1.53 KB
/
gulp-html-compile.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
'use strict';
var gutil = require( 'gulp-util' );
var through = require( 'through2' );
var PluginError = gutil.PluginError;
var PLUGIN_NAME = 'gulp-html-compile';
module.exports = function ( options ) {
options = options || {};
function compiler( file ) {
var name = typeof options.name === 'function' && options.name( file ) || file.relative;
var namespace = options.namespace || 'templates';
var NSwrapper = '(function() {(window["' + namespace + '"] = window["' + namespace + '"] || {})["' + name.replace( /\\/g, '/' ) +'"] = function() { return "';
var template = file.contents.toString().split( '\n' ).join( '' ).replace( /\"/g, '\\"');
return NSwrapper + template + '";};})();';
}
var stream = through.obj(function( file, enc, callback ) {
if ( file.isNull() ) {
this.push( file );
return callback();
}
if ( file.isStream() ) {
this.emit( 'error', new PluginError( PLUGIN_NAME, 'Streams are not supported!' ));
return callback();
}
var filePath = file.path;
try {
var compiled = compiler( file );
file.contents = new Buffer( compiled );
file.path = gutil.replaceExtension( file.path, '.js' );
} catch ( err ) {
this.emit( 'error', new PluginError( PLUGIN_NAME, err, {
fileName: filePath
}));
return callback();
}
this.push( file );
callback();
});
return stream;
};