Skip to content

Commit

Permalink
✨ [feature] 添加bundle分析命令.
Browse files Browse the repository at this point in the history
  • Loading branch information
lanjingling0510 committed May 17, 2017
1 parent e733a77 commit 8dca992
Show file tree
Hide file tree
Showing 14 changed files with 1,778 additions and 43 deletions.
14 changes: 14 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
root = true

[*]
charset = utf-8

indent_style = space
indent_size = 2

end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
trim_trailing_whitespace = false
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
lib
node_modules
.vscode
.azer
57 changes: 57 additions & 0 deletions gulpfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
const path = require('path');
const gulp = require('gulp');
const babel = require('gulp-babel');
const gutil = require('gulp-util');
const colors = gutil.colors;
const NODE_SRC = ['src/**/*.js'];
const resolve = path.resolve;
const relative = path.relative;
const white = colors.cyan;
const cyan = colors.cyan;
const NODE_DEST = resolve('lib');

gulp.task('build', function () {
return gulp.src(NODE_SRC)
.pipe(babel())
.pipe(gulp.dest(NODE_DEST));
});


gulp.task('watch', ['build'], () => {
const watch = require('gulp-watch');
const plumber = require('gulp-plumber');
const del = require('del');

gulp.watch('.babelrc', ['build']);

return watch(NODE_SRC, file => {
const event = file.event;

if (event === 'add' || event === 'change') {
gutil.log(
`${white('[Watcher]')} Compiling '${cyan(getProjectPath(file.path))}' as it was ` +
`${cyan(event === 'change' ? 'changed' : 'added')}...`
);
gulp
.src(file.path, { base: 'src' })
.pipe(plumber())
.pipe(babel())
.pipe(gulp.dest(NODE_DEST));
}

if (event === 'unlink') {
const compiledScriptPath = resolve(NODE_DEST, file.relative);
gutil.log(
`${white('[Watcher]')} Deleting compiled file '${cyan(getProjectPath(compiledScriptPath))}' ` +
"as it's source was deleted..."
);
del.sync(compiledScriptPath);
}
});
});

gulp.task('default', ['watch']);

function getProjectPath(absolutePath) {
return relative(__dirname, absolutePath);
}
24 changes: 20 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
"description": "Analyze the size of multiple git versions of the bundle.",
"main": "./lib/index.js",
"bin": {
"bundleAnalyzer": "./lib/index.js"
"azer": "./lib/index.js"
},
"scripts": {
"build": "babel ./src --out-dir ./lib"
"clean": "rm -rf ./lib",
"start": "npm run clean && gulp",
"build": "npm run clean && babel ./src --out-dir ./lib"
},
"keywords": [
"analyze",
Expand All @@ -19,13 +21,21 @@
"author": "rainie",
"license": "ISC",
"dependencies": {
"blessed": "^0.1.81",
"blessed-contrib": "^4.7.5",
"chalk": "^1.1.3",
"commander": "^2.9.0"
"commander": "^2.9.0",
"filesize": "^3.5.9",
"fs-extra": "^3.0.1",
"inquirer": "^3.0.6",
"lodash": "^4.17.4",
"moment": "^2.18.1"
},
"devDependencies": {
"babel-cli": "^6.24.1",
"babel-core": "^6.24.1",
"babel-eslint": "^7.2.3",
"babel-loader": "^7.0.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-object-rest-spread": "^6.23.0",
"babel-preset-env": "^1.4.0",
Expand All @@ -35,6 +45,12 @@
"eslint-plugin-flowtype": "^2.32.1",
"eslint-plugin-import": "^2.0.1",
"eslint-plugin-jsx-a11y": "^2.2.3",
"eslint-plugin-react": "^6.4.1"
"eslint-plugin-react": "^6.4.1",
"gulp": "^3.9.1",
"gulp-babel": "^6.1.2",
"gulp-plumber": "^1.1.0",
"gulp-sourcemaps": "^2.6.0",
"gulp-util": "^3.0.8",
"gulp-watch": "^4.3.11"
}
}
128 changes: 128 additions & 0 deletions src/azer-add.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
#! /usr/bin/env node

const commander = require('commander');
const fs = require('fs-extra');
const moment = require('moment');
const path = require('path');
const chalk = require('chalk');
const inquirer = require('inquirer');
const _ = require('lodash');
const dir = require('./util/dir.js');
const ROOT_PATH = process.cwd();
const promptMessage = chalk.cyan('bundle-compare-analyzer') + ': ';
// bundle分析存储目录
const DEST_PATH = path.resolve(ROOT_PATH, '.azer');

commander.parse(process.argv);

if (_.isEmpty(commander.args)) {
showError(' 😌 请输入生成的bundle路径.');
}

async function main() {
try {
// 展示已有的版本ID
await showAllVersionID();
// 设置versionID
const versionID = await getVersionID();
// 生成bundle信息
const bundleStats = await generateBundleStats();
// 存储到本地的bundle数据
await writeLocalFile(versionID, bundleStats);

console.log();
console.log(chalk.green('😁 Good Job!'));
console.log();
} catch (err) {
showError(err);
}
}

main();

// 显示已有的版本ID
async function showAllVersionID() {
await fs.ensureDir(DEST_PATH);
const fileNames = await dir
.traverse(DEST_PATH)
.then(stats => stats.map(stat => path.basename(stat.name, '.json')));

if (_.isEmpty(fileNames)) return;

console.log();
console.log(chalk.green('当前已有的bundle版本名称:'));
console.log(chalk.green('.........................'));
fileNames.forEach(name => {
console.log(`${name}\n`);
});
console.log(chalk.green('.........................'));
}

// 获得版本ID
async function getVersionID() {
const pkg = await fs.readJson('./package.json');
const defaultID = `${pkg.version}_${moment().format('MMDDHH:mm:ss')}`;

let schemaVersionID = [
{
type: 'input',
name: 'value',
message: promptMessage + `请输入版本名称(默认为${chalk.green(defaultID)})`,
},
];
const versionIDObj = await inquirer.prompt(schemaVersionID);
return versionIDObj.value || defaultID;
}

// 生成bundle信息
async function generateBundleStats() {
const bundleDir = commander.args.map(value => path.resolve(ROOT_PATH, value));
const promises = bundleDir.map(async value => {
const stats = await dir.traverse(value);
return stats.map(stat => ({
thunk: stat.name.split('.')[0],
ext: path.extname(stat.name),
name: stat.name,
size: stat.stat.size,
}));
});

return Promise.all(promises);
}

// 存储到本地的bundle数据
async function writeLocalFile(versionID, bundleStats) {
const bundleData = {
id: versionID,
stats: _.merge(...bundleStats),
};

await fs.ensureDir(DEST_PATH);

const destPath = path.join(DEST_PATH, `${versionID}.json`);

// 是否覆盖掉之前的bundle文件
if (await fs.pathExists(destPath)) {
let schema = [
{
type: 'confirm',
name: 'confirm',
message: `是否覆盖掉之前生成的${chalk.cyan(versionID)}.json分析文件`,
default: true,
},
];

const result = await inquirer.prompt(schema);
if (!result.confirm) {
process.exit(1);
}
}

// 写入文件中
await fs.writeJson(destPath, bundleData);
}

function showError(error) {
if (error) console.log(`\n ${chalk.magenta(error)}`);
process.exit(1);
}
Loading

0 comments on commit 8dca992

Please sign in to comment.