Skip to content

Commit cb151c7

Browse files
committed
feat(pack): 使用 uglify 进行压缩 (+1 squashed commit)
Squashed commits: [76d15fb] feat(pack): 使用 uglify 进行压缩
1 parent 3e67b01 commit cb151c7

File tree

10 files changed

+258
-118
lines changed

10 files changed

+258
-118
lines changed

.eslintrc.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ globals:
4040
yaml: true
4141
requireUncached: true
4242
spinner: true
43+
logTime: true
4344
mkdirp: true
4445
JSON5: true
4546
YKIT_COMMANDS_PATH: true

lib/global.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
'use strict';
22

33
require('colors');
4+
var moment = require('moment');
5+
var logSymbols = require('log-symbols');
46

57
global.spinner = require('./utils/ora')();
68
global.fs = require('fs');
@@ -37,4 +39,7 @@ global.warn = function () {
3739
global.log = function () {
3840
info('[YKit] '.gray + Array.prototype.join.call(arguments, ' '));
3941
};
42+
global.logTime = function () {
43+
info(logSymbols.info + (' [' + moment().format('YY.MM.DD HH:mm:ss') + '] ').gray + Array.prototype.join.call(arguments, ' '));
44+
};
4045
global.packageJSON = require('../package.json');

lib/models/Project.js

Lines changed: 81 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@ var requireg = require('requireg');
1212
var path = require('path');
1313
var fs = require('fs');
1414

15-
var Config = require('./Config.js'),
16-
Manager = require('../modules/manager.js'),
17-
ExtractTextPlugin = require('extract-text-webpack-plugin');
15+
var Config = require('./Config.js');
16+
var Manager = require('../modules/manager.js');
17+
var ExtractTextPlugin = require('extract-text-webpack-plugin');
1818

1919
var UtilFs = require('../utils/fs.js');
2020
var UtilPath = require('../utils/path.js');
@@ -290,6 +290,7 @@ var Project = function () {
290290
var _this3 = this;
291291

292292
var self = this,
293+
packStartTime = Date.now(),
293294
config = this.config.getConfig();
294295

295296
UtilFs.deleteFolderRecursive(this.cachePath);
@@ -301,35 +302,19 @@ var Project = function () {
301302
}
302303

303304
var compilerProcess = function compilerProcess() {
305+
// 打包前设置
304306
if (opt.sourcemap) {
305307
config.devtool = opt.sourcemap;
306308
}
307-
308309
if (!opt.quiet) {
309310
config.plugins.push(require('../plugins/progressBarPlugin.js'));
310311
}
311-
312312
if (opt.min) {
313-
// variable name mangling
314-
var mangle = true;
315-
if (typeof opt.min === 'string' && opt.min.split('=')[0] === 'mangle' && opt.min.split('=')[1] === 'false') {
316-
mangle = false;
317-
}
318-
319-
config.plugins.push(new webpack.optimize.UglifyJsPlugin({
320-
compress: {
321-
warnings: false
322-
},
323-
mangle: mangle
324-
}));
325313
config.output = config.output.prd;
326314
config.devtool = '';
327315
} else {
328316
config.output = config.output.dev;
329317
}
330-
331-
_this3.fixCss();
332-
333318
if (opt.clean) {
334319
try {
335320
UtilFs.deleteFolderRecursive(config.output.path);
@@ -338,48 +323,90 @@ var Project = function () {
338323
}
339324
}
340325

326+
_this3.fixCss();
327+
341328
webpack(config, function (err, stats) {
342-
globby.sync('**/*.cache', { cwd: config.output.path }).map(function (p) {
329+
var cwd = config.output.path;
330+
331+
globby.sync('**/*.cache', { cwd: cwd }).map(function (p) {
343332
return sysPath.join(config.output.path, p);
344333
}).forEach(function (fp) {
345334
fs.unlinkSync(fp);
346335
});
347336

348-
if (!err) {
349-
async.series(_this3.packCallbacks.map(function (packCallback) {
350-
return function (callback) {
351-
packCallback(opt, stats);
352-
callback(null);
353-
};
354-
}), function (err) {
355-
var statsInfo = stats.toJson({ errorDetails: false });
356-
357-
process.stdout.write('\n' + '\x1b[90m' + '-------------------------- YKIT PACKED ASSETS -------------------------- ' + '\x1b[0m \n\n');
358-
359-
if (statsInfo.errors.length > 0) {
360-
statsInfo.errors.map(function (err) {
361-
error(err.red);
362-
info();
363-
});
364-
}
365-
if (statsInfo.warnings.length > 0) {
366-
statsInfo.warnings.map(function (warning) {
367-
warn(warning.yellow);
368-
info();
369-
});
370-
}
337+
// 压缩
338+
var computecluster = require('compute-cluster');
339+
var cc = new computecluster({
340+
module: sysPath.resolve(__dirname, '../modules/minifyWorker.js'),
341+
max_backlog: -1,
342+
max_processes: 5
343+
});
371344

372-
var assetsInfo = self.config._config.assetsInfo || statsInfo.assets;
373-
assetsInfo.map(function (asset) {
374-
var size = asset.size > 1024 ? (asset.size / 1024).toFixed(2) + ' kB' : asset.size + ' bytes';
375-
if (!/\.cache$/.test(asset.name)) {
376-
log('- '.gray + asset.name + ' - ' + size);
377-
}
378-
});
345+
if (opt.min) {
346+
(function () {
347+
spinner.start();
348+
349+
var assetsInfo = stats.toJson({
350+
errorDetails: false
351+
}).assets;
352+
var processToRun = assetsInfo.length;
353+
354+
assetsInfo.forEach(function (asset) {
355+
cc.enqueue({
356+
opt: opt,
357+
cwd: cwd,
358+
assetName: asset.name
359+
}, function (err) {
360+
if (err) {
361+
error('an error occured:', err);
362+
}
379363

380-
info();
381-
callback(err, stats);
382-
});
364+
processToRun -= 1;
365+
spinner.text = '[Minify] ' + (assetsInfo.length - processToRun) + '/' + assetsInfo.length + ' assets';
366+
367+
if (processToRun === 0) {
368+
cc.exit();
369+
spinner.stop();
370+
logTime('minify complete!');
371+
372+
async.series(self.packCallbacks.map(function (packCallback) {
373+
return function (callback) {
374+
packCallback(opt, stats);
375+
callback(null);
376+
};
377+
}), function (err) {
378+
var statsInfo = stats.toJson({ errorDetails: false });
379+
380+
process.stdout.write('\n' + '\x1b[90m' + '-------------------------- YKIT PACKED ASSETS -------------------------- ' + '\x1b[0m \n\n');
381+
382+
if (statsInfo.errors.length > 0) {
383+
statsInfo.errors.map(function (err) {
384+
error(err.red + '\n');
385+
});
386+
}
387+
if (statsInfo.warnings.length > 0) {
388+
statsInfo.warnings.map(function (warning) {
389+
warn(warning.yellow + '\n');
390+
});
391+
}
392+
393+
var assetsInfo = self.config._config.assetsInfo || statsInfo.assets;
394+
assetsInfo.map(function (asset) {
395+
var size = asset.size > 1024 ? (asset.size / 1024).toFixed(2) + ' kB' : asset.size + ' bytes';
396+
if (!/\.cache$/.test(asset.name)) {
397+
log('- '.gray + asset.name + ' - ' + size);
398+
}
399+
});
400+
401+
var packDuration = Date.now() - packStartTime > 1000 ? Math.floor((Date.now() - packStartTime) / 1000) + 's' : Date.now() - packStartTime + 'ms';
402+
log('Finished in ' + packDuration + '.\n');
403+
404+
callback(err, stats);
405+
});
406+
}
407+
});
408+
});
409+
})();
383410
}
384411
});
385412
};

lib/modules/minifyWorker.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
'use strict';
2+
3+
var path = require('path');
4+
var fs = require('fs');
5+
var jsParser = require('uglify-js').parser;
6+
var jsUglify = require('uglify-js').uglify;
7+
var cssUglify = require('uglifycss');
8+
9+
process.on('message', function (m) {
10+
var opt = m.opt;
11+
var cwd = m.cwd;
12+
var assetName = m.assetName;
13+
14+
if (/\.js$/.test(assetName) || /\.css$/.test(assetName)) {
15+
var content = fs.readFileSync(path.resolve(cwd, assetName), { encoding: 'utf8' });
16+
var minifiedCode = null;
17+
18+
if (path.extname(assetName) === '.js') {
19+
// variable name mangling
20+
var willMangle = true;
21+
if (typeof opt.min === 'string' && opt.min.split('=')[0] === 'mangle' && opt.min.split('=')[1] === 'false') {
22+
willMangle = false;
23+
}
24+
var ast = jsParser.parse(content);
25+
ast = willMangle ? jsUglify.ast_mangle(ast) : ast;
26+
ast = jsUglify.ast_squeeze(ast);
27+
minifiedCode = jsUglify.gen_code(ast, true);
28+
} else if (path.extname(assetName) === '.css') {
29+
minifiedCode = cssUglify.processString(content);
30+
}
31+
32+
minifiedCode && fs.writeFileSync(path.resolve(cwd, assetName), minifiedCode, { encoding: 'utf8' });
33+
}
34+
35+
process.send('complete');
36+
});

lib/plugins/progressBarPlugin.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ function ProgressBarPlugin() {
2323
var dateFormat = 'YY.MM.DD HH:mm:ss';
2424
spinner.text = '\x1b[90m' + '[' + moment().format(dateFormat) + '] build complete!' + '\x1b[0m';
2525
spinner.stopAndPersist(logSymbols.info);
26+
spinner.text = '';
2627
}
2728
}
2829
});

package.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
"cli-cursor": "^1.0.2",
2222
"cli-spinners": "^0.3.0",
2323
"colors": "^1.1.2",
24+
"compute-cluster": "0.0.9",
2425
"connect": "^3.4.1",
2526
"css-loader": "^0.23.1",
2627
"extend": "^3.0.0",
@@ -48,6 +49,8 @@
4849
"serve-static": "^1.11.1",
4950
"style-loader": "^0.13.1",
5051
"through2": "^2.0.1",
52+
"uglify-js": "^1.3.5",
53+
"uglifycss": "0.0.25",
5154
"webpack": "^1.13.1",
5255
"webpack-md5-hash": "0.0.5"
5356
},

src/global.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
'use strict';
22

33
require('colors');
4+
const moment = require('moment');
5+
const logSymbols = require('log-symbols');
46

57
global.spinner = require('./utils/ora')();
68
global.fs = require('fs');
@@ -37,4 +39,7 @@ global.warn = function() {
3739
global.log = function() {
3840
info(('[YKit] ').gray + Array.prototype.join.call(arguments, ' '));
3941
};
42+
global.logTime = function() {
43+
info(logSymbols.info + (' [' + moment().format('YY.MM.DD HH:mm:ss') + '] ').gray + Array.prototype.join.call(arguments, ' '));
44+
};
4045
global.packageJSON = require('../package.json');

0 commit comments

Comments
 (0)