UNPKG

18.9 kBJavaScriptView Raw
1'use strict';
2var processPath = process.cwd().replace(/\\/g, "/")
3 , fsExtra = require('fs-extra')
4 , del = require('del');
5
6// delete local node_modules
7del.sync('node_modules/@omnia/foundation/node_modules');
8
9
10var gulp = require('gulp')
11 , glob = require('glob')
12 , chokidar = require('chokidar')
13 , fs = require('fs')
14 , argv = require('yargs').argv
15 , $ = require('gulp-load-plugins')({
16 pattern: [
17 'gulp-*'
18 ],
19 rename: {
20 }
21 })
22 , timestamp = require('console-timestamp')
23 , path = require('path')
24 , webpack = require("webpack")
25 , namedModulesPlugin = require('webpack/lib/NamedModulesPlugin')
26 , gutil = require("gulp-util")
27 , merge = require('webpack-merge')
28 , exec = require('child_process').exec
29 , jsonfile = require('jsonfile')
30 , extend = require('deep-extend')
31 , timestamp = require('console-timestamp')
32 , path = require('path')
33 , omfWebpackPlugins = require('./services/omf.webpack.plugins')
34 , utils = require('@omnia/tooling/utils')
35 , core = require('@omnia/tooling/core');
36
37var appConfig = {};
38mergeConfig();
39core.registerBuildTask({ type: core.BuildType.BeforeBuild, order: 9, task: beforeBuild });
40core.registerBuildTask({ type: core.BuildType.AfterBuild, order: 20, task: afterBuild });
41
42
43//gulp.task('aot-compile', function (cb) {
44// mergeConfig()
45// .then(aotCompile)
46// .then(cb);
47//})
48
49//gulp.task('webpack-bundle', function (cb) {
50// mergeConfig()
51// .then(webpackBundle)
52// .then(cb);
53//});
54
55
56gulp.task('omf-watch-webpack', function () {
57 var listFilesBundling = [];
58 process.on('uncaughtException', function (err) {
59 console.log(err);
60 });
61
62 var watchAngular = chokidar.watch(appConfig.angular.webpack.watch, {
63 ignored: /[\/\\]\./,
64 persistent: true
65 });
66
67 watchAngular.on('ready', function () {
68 watchAngular
69 .on('change', function (filePath) {
70 if (listFilesBundling.indexOf(filePath) === -1) {
71 listFilesBundling.push(filePath);
72 webpackCompile(appConfig.angular.webpack.basePath, appConfig.angular.webpack.flatModules, appConfig.angular.webpack.ignoreFiles, filePath, function () {
73 if (listFilesBundling.indexOf(filePath) > -1)
74 listFilesBundling.splice(listFilesBundling.indexOf(filePath), 1)
75 }, true);
76 }
77 });
78 });
79});
80
81function beforeBuild() {
82 return new Promise(function (resolve, reject) {
83 fsExtra.copySync('node_modules/@omnia/foundation/task/external/node_modules/bin', processPath + '/node_modules/.bin');
84 del.sync('node_modules/@types/node');
85 del.sync('node_modules/@omnia/foundation/node_modules');
86 resolve();
87 });
88}
89
90function afterBuild() {
91 return new Promise(function (resolve, reject) {
92 aotCompile()
93 .then(webpackBundle)
94 .then(resolve)
95 });
96}
97
98function aotCompile() {
99 return new Promise(function (resolve, reject) {
100 console.log(timestamp('[hh:mm:ss]') + ' Aot compile running...');
101
102 if (!enableRunAot() && (process.argv.length === 0 || process.argv[process.argv.length - 1] !== '--force-aot')) {
103 console.warn('Aot compile disabled in environment.json');
104 resolve();
105 return;
106 }
107 if (appConfig.angular.aot.cleanBefore && appConfig.angular.aot.cleanBefore.length > 0) {
108 del.sync(appConfig.angular.aot.cleanBefore);
109 }
110 jsonfile.writeFileSync('./omf.tsconfig.aot.json', appConfig.angular.aot.ngc);
111 exec('"node_modules/.bin/ngc" -p ./omf.tsconfig.aot.json', function (err, stdout, stderr) {
112 if (stdout)
113 console.log(stdout);
114 if (stderr)
115 console.log(stderr);
116 if (err !== null) {
117 resolve(err);
118 return;
119 }
120 else {
121 if (appConfig.angular.aot.compileAotTsFiles && appConfig.angular.aot.compileAotTsFiles.length > 0) {
122 del.sync('node_modules/@types/node');
123 gulp.src(appConfig.angular.aot.typesForCompileAotTsFiles.concat(appConfig.angular.aot.compileAotTsFiles))
124 .pipe($.tsc({
125 "target": "es5",
126 "module": "commonjs",
127 "moduleResolution": "node",
128 "declaration": false,
129 "sourceMap": false,
130 "removeComments": false,
131 "noImplicitAny": false,
132 "emitDecoratorMetadata": true,
133 "experimentalDecorators": true,
134 "types": []
135 }))
136 .pipe(gulp.dest('.'))
137 .on('end', function () {
138 doWebpackCompile(resolve);
139 });
140 }
141 else {
142 doWebpackCompile(resolve);
143 }
144 }
145 });
146 })
147
148 function doWebpackCompile(resolve) {
149 if (appConfig.angular.aot.webpackCompileFiles && appConfig.angular.aot.webpackCompileFiles.length > 0) {
150 var totalFiles = 0;
151 var countLoop = 0;
152 for (var i = 0; i < appConfig.angular.aot.webpackCompileFiles.length; i++) {
153 glob(appConfig.angular.aot.webpackCompileFiles[i], function (err, files) {
154 countLoop++;
155 totalFiles = totalFiles + files.length;
156 if (totalFiles === 0 && countLoop === appConfig.angular.aot.webpackCompileFiles.length) {
157 console.log(timestamp('[hh:mm:ss]') + ' Aot compile finished');
158 resolve();
159 }
160 for (var k = 0; k < files.length; k++) {
161 webpackCompile(appConfig.angular.webpack.basePaths, appConfig.angular.webpack.flatModules, appConfig.angular.webpack.ignoreFiles, files[k], function () {
162 totalFiles = totalFiles - 1;
163 if (totalFiles === 0) {
164 if (appConfig.angular.aot.copyOutputAotFilesToTenantResources && appConfig.angular.aot.copyOutputAotFilesToTenantResources.length > 0) {
165 var count = 0;
166 for (var j = 0; j < appConfig.angular.aot.copyOutputAotFilesToTenantResources.length; j++) {
167 gulp.src(appConfig.angular.aot.copyOutputAotFilesToTenantResources[j].source)
168 .pipe(gulp.dest(appConfig.angular.aot.copyOutputAotFilesToTenantResources[j].target))
169 .on('end', function () {
170 count++;
171 if (count === appConfig.angular.aot.copyOutputAotFilesToTenantResources.length) {
172 if (appConfig.angular.aot.cleanAfter && appConfig.angular.aot.cleanAfter.length > 0) {
173 del.sync(appConfig.angular.aot.cleanAfter);
174 }
175 console.log(timestamp('[hh:mm:ss]') + ' Aot compile finished');
176 resolve();
177 }
178 });
179 }
180 }
181 else {
182 if (appConfig.angular.aot.cleanAfter && appConfig.angular.aot.cleanAfter.length > 0) {
183 del.sync(appConfig.angular.aot.cleanAfter);
184 }
185 console.log(timestamp('[hh:mm:ss]') + ' Aot compile finished');
186 resolve();
187 }
188 }
189 });
190 }
191 });
192 }
193 }
194 else {
195 if (appConfig.angular.aot.cleanAfter && appConfig.angular.aot.cleanAfter.length > 0) {
196 del.sync(appConfig.angular.aot.cleanAfter);
197 }
198 console.log(timestamp('[hh:mm:ss]') + ' Aot compile finished');
199 resolve();
200 }
201 }
202}
203
204function webpackBundle(allowLog) {
205 return new Promise(function (resolve, reject) {
206 console.log(timestamp('[hh:mm:ss]') + ' Webpack bundle running...');
207 var srcfiles = appConfig.angular.webpack.compileFiles;
208 var totalFiles = 0;
209 var countLoop = 0;
210
211 for (var i = 0; i < srcfiles.length; i++) {
212 glob(srcfiles[i], function (err, files) {
213 countLoop++;
214 totalFiles = totalFiles + files.length;
215 for (var k = 0; k < files.length; k++) {
216 webpackCompile(appConfig.angular.webpack.basePaths, appConfig.angular.webpack.flatModules, appConfig.angular.webpack.ignoreFiles, files[k], function () {
217 totalFiles = totalFiles - 1;
218 if (totalFiles === 0 && countLoop === srcfiles.length) {
219 console.log(timestamp('[hh:mm:ss]') + ' Webpack bundle finished');
220 resolve();
221 }
222 }, allowLog);
223 }
224 });
225 }
226 if (srcfiles.length === 0) {
227 console.log(timestamp('[hh:mm:ss]') + ' Webpack bundle finished');
228 resolve();
229 }
230 })
231}
232
233
234function webpackCompile(basePaths, flatModules, ignoreFiles, destPath, callBack, allowLog) {
235 var isSelfResolveModule = false;
236 var isCompile = false;
237 if (!isMatchIgnoreFiles(ignoreFiles, destPath) && destPath.indexOf('.ngsummary.js') === -1) {
238 let stream = fs.readFileSync(destPath, 'utf8');
239 isCompile = stream.indexOf('webpackJsonp([0],{') !== 0;
240 if (isCompile) {
241 isSelfResolveModule = stream.indexOf('.OmniaControl({') > -1 || stream.indexOf('.OmniaAdminControl({') > -1 || stream.indexOf('.NgModule({') > -1 || stream.indexOf('.Component({') > -1
242 || stream.indexOf('Extensibility_1.TemplateId') > -1 || stream.indexOf('Extensibility_1.OmniaControl') > -1 || stream.indexOf('<<webpack-resolve-module>>') > -1
243 }
244 }
245 if (isCompile) {
246 var namedModulesReplacements = [];
247 for (var i = 0; i < basePaths.length; i++) {
248 namedModulesReplacements.push({
249 pattern: new RegExp(basePaths[i].replace(/\//g, "\\/") + "\\/", 'g'),
250 replace: ""
251 });
252 }
253 namedModulesReplacements.push({
254 pattern: /\/node_modules/g,
255 replace: ""
256 });
257 fs.appendFileSync(destPath, '\r\n //webpack-eof');
258 destPath = "./" + destPath.replace(/[/\\*]/g, "/");
259 var fileName = destPath.substring(destPath.lastIndexOf('/'));
260 webpack(merge(require("./config/webpack.config.js"), {
261 entry: {
262 'external': './task/config/external.js',
263 'app': destPath
264 },
265 externals: [
266 function (context, request, callback) {
267 if (destPath.indexOf(request.replace("./", "")) === -1 || destPath.substring(destPath.indexOf(request.replace("./", "")), destPath.length) !== request.replace("./", "")) {
268 return callback(null, "__webpack_require__('" + request.toLowerCase() + "')");
269 }
270 else {
271 callback();
272 }
273 }
274 ],
275 cache: false,
276 output: {
277 pathinfo: true,
278 filename: destPath.replace("./", ''),
279 },
280 plugins: [
281 new webpack.optimize.CommonsChunkPlugin({ name: 'external', filename: 'node_modules/@omnia/foundation/task/temp/external.bundle.js' }),
282 new omfWebpackPlugins.NamedModulesPlugin({
283 replacements: namedModulesReplacements
284 }),
285 new omfWebpackPlugins.ReplaceBundlePlugin([
286 {
287 partten: /\/\/# sourceMappingURL[\s\S]+\/\/webpack-eof/g,
288 replacement: function (match) {
289 return '//webpack-eof'
290 }
291 },
292 {
293 partten: /\/\/webpack-eof[\s\S]+}\,\[(.*?)\]/g,
294 replacement: function (match) {
295 return '}},[]'
296 }
297 },
298 {
299 partten: /"use strict";[\s\S]+"use strict";/g,
300 replacement: '"use strict";'
301 },
302 {
303 partten: /\/\* no static exports found[\s\S]+function\(module, exports, __webpack_require__\) {/i,
304 replacement: function (match) { return "function(module, exports, __webpack_require__) {"; }
305 },
306 {
307 partten: /\/\* no static exports found[\s\S]+function\(module, exports\) {/i,
308 replacement: function (match) { return "function(module, exports) {"; }
309 },
310 {
311 partten: /\/\* no static exports found[\s\S]+function\(module, exports\) {/i,
312 replacement: function (match) { return "function(module, exports) {"; }
313 },
314 {
315 partten: new RegExp("__webpack_require__\\(\/\\*(.*)\\)", 'g'),
316 replacement: function (match) {
317 return match
318 .replace("/*!", "'")
319 .replace(/\*\/(.*?)\){1}/i, "')")
320 .replace(/ /g, "")
321 .replace(/'(.*?)'/i, function (requireModulePath) {
322 requireModulePath = requireModulePath.replace(/'/g, "");
323 if (requireModulePath.indexOf(".") === 0) {
324 var requireModulePath = path.resolve(path.dirname(destPath), requireModulePath);
325 requireModulePath = requireModulePath.replace(/\\/g, "/");
326 for (var i = 0; i < basePaths.length; i++) {
327 requireModulePath = requireModulePath.replace(utils.root(basePaths[i]).replace(/\\/g, "/"), "");
328 }
329 requireModulePath = requireModulePath
330 .replace(utils.root('TenantResources').replace(/\\/g, "/") + '/~/', "")
331 .replace(utils.root('.').replace(/\\/g, "/") + '/~/', "")
332 .replace(utils.root('.').replace(/\\/g, "/"), "")
333 .trim("/");
334 if (requireModulePath.indexOf("/") === 0)
335 requireModulePath = requireModulePath.substring(1, requireModulePath.length);
336 if (requireModulePath.indexOf("node_modules/") === 0)
337 requireModulePath = requireModulePath.replace(/node_modules\//i, "");
338 if (destPath.indexOf(requireModulePath + '.js') > -1) {
339 console.log('have recursive import self : ' + destPath);
340 }
341 }
342
343 return "'" + requireModulePath.toLowerCase().replace("@omnia/foundation/extensibility/typings/", "@omnia/foundation/extensibility/") + "'";
344 });
345 }
346 },
347 {
348 skip: !isSelfResolveModule,
349 partten: /webpackJsonp\(\[0\],{[\s\S]+":/g,
350 replacement: function (match) {
351 var moduleId = match.match(/"(.*?)"/)[1]
352 return "omfExecuteModules.push('" + moduleId + "'); ";
353 },
354 insertToEOF: true
355 },
356 {
357 partten: /;;/g,
358 replacement: ';'
359 },
360 ])
361 ]
362 }), function (err, stats) {
363 if (err) throw new gutil.PluginError("webpack", err);
364 })
365 .plugin("done", function () {
366 if (allowLog)
367 console.log('bundle completed - ' + destPath);
368 if (callBack !== undefined)
369 callBack();
370 });
371 }
372 else {
373 if (callBack !== undefined)
374 callBack();
375 }
376}
377
378function isMatchIgnoreFiles(ignoreFiles, filePath) {
379 var isMatch = false
380 for (var i = 0; i < ignoreFiles.length; i++) {
381 if (filePath.indexOf(ignoreFiles[i]) > -1) {
382 isMatch = true;
383 return isMatch;
384 }
385 }
386
387 return isMatch;
388}
389
390function enableRunAot() {
391 var result = true;
392 var processPath = process.cwd().replace(/\\/g, "/");
393
394 if (fs.existsSync(processPath + '/environment.json')) {
395 try {
396 var config = require(processPath + '/environment.json');
397 if (config.Angular && config.Angular && config.Angular.AOT && config.Angular.AOT.RunOnBuild === false)
398 result = false
399 }
400 catch (err) {
401 console.log(err);
402 }
403 }
404
405 return result;
406}
407
408function mergeConfig() {
409 appConfig = require('./config/app.json');
410 var config = core.getConfig('/TaskRunner/Tasks/Angular/task.config.json');
411 if (config !== null)
412 utils.extend(appConfig, config)
413}