UNPKG

2.33 kBJavaScriptView Raw
1'use strict';
2
3var fs = require('fs'),
4 path = require('path'),
5 glob = require('glob'),
6 minimatch = require('minimatch'),
7 changed = require('gulp-changed'),
8 webpack = require('gulp-webpack');
9
10function to_array(obj) {
11 return Array.isArray(obj) ? obj : (obj ? [obj] : []);
12}
13
14module.exports = function(options) {
15 var src = path.join(options.paths.scripts.cwd, options.paths.scripts.glob),
16 dest = path.join(options.paths.dest, options.paths.scripts.dest);
17
18 var filters = []
19 .concat(to_array(options.files.filter))
20 .concat(to_array(options.paths.scripts.filter))
21 .map(function(filter) {
22 return minimatch.filter(filter);
23 });
24
25 function filterGlobs(file) {
26 if (!filters.length) {
27 return true;
28 }
29
30 for (var key in filters) {
31 if (filters[key](file)) {
32 return true;
33 }
34 }
35
36 return false;
37 }
38
39 function compile(stream, onError) {
40 var config = {
41 entry: {},
42 resolve: {
43 extensions: ['', '.js', '.coffee', '.litcoffee']
44 },
45 module: {
46 loaders: [
47 { test: /\.(?:lit)?coffee$/, loader: require.resolve('coffee-loader') }
48 ]
49 },
50 output: {
51 path: dest,
52 filename: '[name].js'
53 }
54 };
55
56 glob
57 .sync(path.join(options.paths.scripts.cwd, options.paths.scripts.glob))
58 .forEach(function(file) {
59 if (!/[\/\\]_/.test(file) && filterGlobs(file)) {
60 var fixed_file = path.relative(options.paths.scripts.cwd, file),
61 fixed_entry = options.bundle && options.bundle.compact ? '' : '$1$2',
62 fixed_keyname = fixed_file.replace(/(?:(\/?)(\w+))?.(?:lit)?coffee$/, fixed_entry);
63
64 var dest_file = path.join(dest, fixed_keyname + '.js');
65
66 if (!fs.existsSync(dest_file) || (fs.statSync(file).mtime > fs.statSync(dest_file).mtime)) {
67 config.entry[fixed_keyname] = file;
68 }
69 }
70 });
71
72 if (options.env.debug === true) {
73 config.devtool = '#inline-source-map';
74 }
75
76 return stream.pipe(webpack(config)).on('error', onError);
77 }
78
79 function ifChanged(stream, onError) {
80 return stream.pipe(changed(dest, {
81 extension: '.js'
82 })).on('error', onError);
83 }
84
85 return {
86 src: src,
87 dest: dest,
88 pipe: compile,
89 check: ifChanged
90 };
91};