This repository has been archived by the owner on Aug 23, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·240 lines (224 loc) · 7.15 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
#!/usr/bin/env node
// Copyright © 2015-2017 STRG.AT GmbH, Vienna, Austria
//
// This file is part of the The SCORE Framework.
//
// The SCORE Framework and all its parts are free software: you can redistribute
// them and/or modify them under the terms of the GNU Lesser General Public
// License version 3 as published by the Free Software Foundation which is in the
// file named COPYING.LESSER.txt.
//
// The SCORE Framework and all its parts are distributed without any WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
// PARTICULAR PURPOSE. For more details see the GNU Lesser General Public
// License.
//
// If you have not received a copy of the GNU Lesser General Public License see
// http://www.gnu.org/licenses/.
//
// The License-Agreement realised between you as Licensee and STRG.AT GmbH as
// Licenser including the issue of its valid conclusion and its pre- and
// post-contractual effects is governed by the laws of Austria. Any disputes
// concerning this License-Agreement including the issue of its valid conclusion
// and its pre- and post-contractual effects are exclusively decided by the
// competent court, in whose district STRG.AT GmbH has its registered seat, at
// the discretion of STRG.AT GmbH also the competent court, in whose district the
// Licensee has his registered seat, an establishment or assets.
const DIR = process.cwd();
/*
* Imports
*/
const argv = require('minimist')(process.argv.slice(2));
const _ = require('lodash');
const requirejs = require('requirejs');
const chokidar = require('chokidar');
const Path = require('path');
const ARGV = [
'w', 'watch',
'm', 'minify',
'v', 'verbose',
'n', 'no-source-urls',
'c', 'config',
'h', 'help',
'x', 'exclude-almond'
];
/*
* Parse CLI options
*/
if (argv.help || argv.h) {
require('./help');
return;
}
const configFile = argv.config || argv.c;
const options = (configFile) ?
require(Path.resolve(DIR, configFile)) :
require(Path.resolve(DIR, 'build.config.js'));
const watch = argv.watch || argv.w || false;
const minify = argv.minify || argv.m || false;
const verbose = argv.verbose || argv.v || false;
const noSourceUrls = argv['no-source-urls'] || argv.n || false;
const excludeAlmond = argv['exclude-almond'] || argv.x || false;
/*
* Constants and additional config
*/
const IGNORE = new RegExp('(%s)'.replace('%s',
[options.out, options.outDev].join('|')));
const BASEDIR = options.baseDir;
const FILE_TYPES = options.fileTypes;
const FILE_TYPES_REGEX = new RegExp('\\.(%s)$'
.replace('%s', FILE_TYPES.join('|')));
const FILES = BASEDIR + '/**/*.(%s)'.replace('%s',
FILE_TYPES.join('|'));
const DEBOUNCE = 100;
const OUT_FILE = (minify) ? options.out : options.outDev;
function validateArgv(argv) {
const invalids = _(argv).keys().reduce((result, k) => {
if (!_(['_'].concat(ARGV)).includes(k)) {
result.push(k);
}
return result;
}, []);
if (invalids.length > 0) {
console.error('Error: Unrecognized arguments: ' + invalids.join(', '));
throw new TypeError('Unrecognized arguments');
}
}
validateArgv(argv);
function relativeModulePath(path, removeExt) {
const relPath = Path.relative(BASEDIR, require.resolve(path));
if (removeExt) {
return relPath.replace(new RegExp(`\.${removeExt}$`), '');
}
return relPath;
}
/*
* Base Config for RequireJS Optimizer
*/
function config(paths) {
const conf = {
baseUrl: BASEDIR,
mainConfigFile: options.mainConfigFile || [],
out: OUT_FILE,
findNestedDependencies: true,
optimize: (minify) ? 'uglify' : 'none',
useSourceUrl: !minify && !noSourceUrls,
mustache: {
resolve: function (name) {
return name + '.mustache';
}
},
paths: {
'lib/template': relativeModulePath('requirejs-mustache-loader/lib/template.mustache', 'mustache'),
'template': relativeModulePath('requirejs-mustache-loader', 'js'),
'text': relativeModulePath('requirejs-text', 'js'),
'mustache': relativeModulePath('mustache', 'js')
},
stubModules: ['text', 'lib/template'],
include: [].concat(paths)
};
if (excludeAlmond) {
// Include requirejs in build
conf.paths['requireLib'] = relativeModulePath('requirejs/require', 'js');
conf.include.push('requireLib');
} else {
// Resolve and include almond for single file bundle
conf.name = relativeModulePath('almond', 'js');
}
return conf;
}
/*
* Watcher Singleton
* File-collector and asynchronous Build-Hub
*/
const watcher = chokidar.watch(FILES, {
ignored: IGNORE,
ignoreInitial: false,
persistent: watch,
atomic: 100,
cwd: '.'
});
/*
* Helpers
*/
function stripBase(path) {
return path.replace(new RegExp(`^${BASEDIR}\/`), '');
}
function stripJSExtension(path) {
if (/\.mustache$/.test(path)) {
return 'template!' + stripBase(path);
}
return path.replace(/\.js$/, '');
}
function toPathList(watched) {
return _(watched).reduce((result, files, dir) => {
const paths = files.filter((file) =>
FILE_TYPES_REGEX.test(file)
).reduce((result, file) => {
result.push(dir + '/' + file);
return result;
}, [])
.map(stripBase)
.map(stripJSExtension);
if (paths.length) return result.concat(paths);
return result;
}, []).sort();
}
/*
* Bundling
*/
function logBuildResponse(buildResponse, stamp) {
if (verbose) {
console.log(buildResponse);
}
console.log('\x1b[32m' + 'Bundling complete:' + '\x1b[0m',
(new Date().getTime() - stamp) / 1000 + 's');
}
function logBuildError(err) {
console.error('\x1b[31m' + 'Build failed.', '\x1b[0m');
if (watch) console.error(err.originalError);
}
function bundle(config) {
const stamp = new Date().getTime();
if (!watch) console.log('Bundling started.');
if (verbose) console.log(config);
// Call optimize without error callback. Otherwise
// the optimizer catches all exceptions and the script
// exits with 0 instead of 1
if (!watch) {
return requirejs.optimize(config, (buildResponse) =>
logBuildResponse(buildResponse, stamp));
}
return requirejs.optimize(config, (buildResponse) =>
logBuildResponse(buildResponse, stamp), logBuildError);
}
/*
* Initialize
*/
watcher.on('ready', () => {
const makeBundle = _.debounce(() => {
bundle(
config(
toPathList(watcher.getWatched())
)
);
}, DEBOUNCE);
if (watch) {
console.log('Watcher started.');
watcher.on('all', (event, path) => {
switch (event) {
case 'add':
console.log('Add file:', path);
makeBundle();
break;
case 'change':
makeBundle();
break;
case 'unlink':
console.log('Remove file:', path);
makeBundle();
break;
}
});
}
makeBundle();
});