forked from PastVu/pastvu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.js
executable file
·256 lines (230 loc) · 8.51 KB
/
build.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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
#!/usr/bin/env node
/**
* Copyright: The PastVu contributors.
* GNU Affero General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/agpl.txt)
*/
'use strict';
require('./bin/run');
const start = Date.now();
const fs = require('fs');
const path = require('path');
const sys = require('util');
const step = require('step');
const requirejs = require('requirejs');
const less = require('less');
const Utils = require('./commons/Utils');
const lessCompileOptions = {
compress: true,
silent: false,
path: 'public/style/',
color: true,
strictImports: true,
};
const requireBuildConfig = {
appDir: 'public/',
baseUrl: 'js',
dir: 'public-build',
keepBuildDir: false,
optimize: 'none', // We will minify the built files after the optimizer runs.
normalizeDirDefines: 'all', // Make define() calls normalized correctly to withstand post hoc minification.
skipDirOptimize: false, //Оптимизировать только модули (modules array), не трогая остальные js
optimizeCss: 'none', //Не трогаем css
preserveLicenseComments: false, //Удаляем лицензионные комментарии
removeCombined: false, //Не удаляем файлы, которые заинлайнились в модуль
inlineText: true, //Включать ли в модули контент, загруженный плагином text
logLevel: 0,
mainConfigFile: 'public/js/_mainConfig.js',
paths: {
'lib/geocoordsparser': 'empty:', // Exclude geocoordsparser processing, as it fails on spread syntax (https://github.com/requirejs/r.js/issues/971)
},
modules: [
{
//Виртуальный модуль, содержащий общие модули, которые надо исключать из частных модулей
name: 'commonExcludes',
create: true, //set crecate: true if 'commonExcludes' is not a module that exists before a build
include: [
'domReady', 'text', 'css', 'lib/require/plugins/require-css/normalize',
'jquery', 'underscore', 'knockout', 'knockout.mapping', 'lib/doT', 'moment',
'noty', 'noty.layouts', 'noty.themes/pastvu',
'Browser', 'Utils', 'socket', 'router', 'Params', 'globalVM',
'm/_moduleCliche', 'renderer',
'model/Photo', 'model/User', 'model/storage', 'intl',
],
},
{
name: '_mainConfig', //Компилируем конфигурацию, чтобы включить туда общую зависимость 'lib/JSExtensions'
},
{
name: 'module/appMain',
include: [
'socket.io', 'lib/doT',
'm/common/auth', 'm/common/top', 'm/common/foot',
'm/main/commentsFeed', 'm/main/mainPage', 'm/main/bottomPanel',
'm/map/map', 'm/map/marker', 'm/map/navSlider',
'm/photo/photo', 'm/photo/gallery',
'm/diff/newsList', 'm/diff/news',
'm/comment/comments',
'm/user/brief', 'm/user/profile', 'm/user/userPage',
'errors/Application', 'errors/Timeout',
],
exclude: ['lib/require/plugins/require-css/normalize'], // normalize надо исключать, т.к. он почему-то попадает в сборку https://github.com/guybedford/require-css#basic-usage
},
{
name: 'm/diff/about',
exclude: ['commonExcludes'],
},
{
name: 'm/user/comments',
exclude: ['commonExcludes'],
},
{
name: 'm/user/photoUpload',
exclude: ['commonExcludes'],
},
{
name: 'm/comment/hist',
exclude: ['commonExcludes'],
},
{
name: 'm/photo/hist',
exclude: ['commonExcludes'],
},
{
name: 'm/common/share',
exclude: ['commonExcludes'],
},
{
name: 'm/user/subscr',
exclude: ['commonExcludes'],
},
{
name: 'm/user/settings',
exclude: ['commonExcludes', 'bs/collapse'],
},
{
name: 'm/user/sessions',
exclude: ['commonExcludes', 'bs/collapse'],
},
{
name: 'm/user/session',
exclude: ['commonExcludes'],
},
{
name: 'm/user/manage',
exclude: ['commonExcludes', 'bs/collapse'],
},
{
name: 'm/region/select',
exclude: ['commonExcludes'],
},
{
name: 'm/common/reason',
exclude: ['commonExcludes'],
},
],
};
let lessFiles = [];
step(
// Ищем less-файлы для компиляции и создаем плоский массив
function searchLess() {
Utils.walkParallel({ dir: path.normalize('./' + requireBuildConfig.appDir + 'style'), excludeFolders: ['bs', 'fonts'], onDone: (e, files) => {
if (e) {
console.dir(e);
process.exit(1);
}
lessFiles = Utils.filesListProcess(files, requireBuildConfig.appDir + 'style/', '', function getOnlyLess(element) {
return ~element.indexOf('.less');
});
this();
} });
},
//Компилируем less
function startCompile() {
lessCompile(lessFiles, this);
},
// Собираем require
function requireBuild() {
console.log('~~~ Start r.js build ~~~');
requirejs.optimize(requireBuildConfig, (/*buildResponse*/) => {
//buildResponse is just a text output of the modules
//included. Load the built file for the contents.
//Use requireBuildConfig.out to get the optimized file contents.
//var contents = fs.readFileSync(requireBuildConfig.out, 'utf8');
console.dir('Require build finished');
this();
});
},
//Удаляем less из собранной директории
function removeLessFromBuild() {
console.dir('Removing Less from build');
Utils.walkParallel({ dir: path.normalize(requireBuildConfig.dir + '/style'), onDone: (e, files) => {
if (e) {
console.dir(e);
process.exit(1);
}
lessFiles = Utils.filesListProcess(files, null, '', function getOnlyLess(element) {
return ~element.indexOf('.less');
});
lessFiles.forEach(item => {
fs.unlinkSync(item);
});
this();
} });
},
function finish(e) {
if (e) {
console.dir(e);
process.exit(1);
}
console.dir('Build complete. Ok in ' + (Date.now() - start) / 1000 + 's');
process.exit(0);
}
);
function lessCompile(files, done) {
let input;
let output;
let fd;
let i = 0;
next();
function next() {
input = files[i++];
if (!input) {
return done();
}
output = lessCompileOptions.path + input.replace('.less', '.css');
fs.readFile(lessCompileOptions.path + input, 'utf-8', parseLessFile);
}
function parseLessFile(e, data) {
if (e) {
sys.puts('Error to read less ' + (lessCompileOptions.path + input) + ' file: ' + e.message);
process.exit(1);
}
console.dir('Compiling LESS ' + lessCompileOptions.path + input);
less.render(data, {
paths: [lessCompileOptions.path + path.dirname(input)],
filename: path.basename(input),
strictImports: lessCompileOptions.strictImports,
compress: lessCompileOptions.compress,
}).then(result => {
try {
const css = result.css;
if (css) {
fd = fs.openSync(output, 'w');
fs.writeSync(fd, css, 0, 'utf8');
fs.closeSync(fd);
}
next();
} catch (err) {
console.error(err, lessCompileOptions);
process.exit(1);
}
}, err => {
if (!lessCompileOptions.silent) {
console.error(err.toString({
stylize: lessCompileOptions.color && less.lesscHelper.stylize,
}));
}
process.exit(1);
});
}
}