UNPKG

1.9 kBJavaScriptView Raw
1'use strict';
2
3var PLUGIN_NAME = 'gulp-tarima';
4
5var through2 = require('through2'),
6 gutil = require('gulp-util'),
7 path = require('path');
8
9var File = gutil.File,
10 PluginError = gutil.PluginError;
11
12var tarima = require('tarima');
13
14module.exports = function(options, callback) {
15 if (typeof options === 'string') {
16 options = {
17 filename: options
18 };
19 }
20
21 options = options || {};
22
23 options.wrapper = callback || options.wrapper || function(code) {
24 return code + '\nmodule.exports = JST;';
25 };
26
27 var files = [];
28
29 function write(file, enc, cb) {
30 if (file.isStream()) {
31 return cb(new PluginError(PLUGIN_NAME, 'Streaming not supported'));
32 }
33
34 var partial = tarima.parse(file.path, file.contents.toString(), options);
35
36 if (file.isBuffer()) {
37 var data = options.locals || options.data || file.data;
38
39 file.path = path.join(path.dirname(file.path), partial.params.name + '.' + partial.params.ext);
40 file.keypath = partial.params.keypath;
41
42 var code = partial.compile(data);
43
44 var undef = code.indexOf('module.exports') === -1 && /^\s*function/.test(code);
45
46 if (!options.filename && partial.params.ext === 'js' && undef) {
47 code = 'module.exports = ' + code + ';';
48 }
49
50 file.contents = new Buffer(code);
51 }
52
53 if (options.filename && file.path.indexOf('.js') > -1) {
54 files.push(partial);
55 cb(null);
56 } else {
57 cb(null, file);
58 }
59 }
60
61 function end(cb) {
62 if (options.filename) {
63 var code = tarima.bundle(files, options);
64
65 this.push(new File({
66 path: options.filename,
67 contents: new Buffer(code)
68 }));
69
70 cb(null);
71 } else {
72 cb();
73 }
74 }
75
76 return through2.obj(write, end);
77};
78
79// expose tarima api
80for (var key in tarima) {
81 if (Object.prototype.hasOwnProperty.call(tarima, key)) {
82 module.exports[key] = tarima[key];
83 }
84}