-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbenchmark.js
More file actions
338 lines (279 loc) · 13.7 KB
/
benchmark.js
File metadata and controls
338 lines (279 loc) · 13.7 KB
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import { rmSync, mkdirSync, existsSync, writeFileSync, readFileSync } from 'fs';
import { execSync } from 'child_process';
import { join } from 'path';
const TEMP_DIR = './temp';
const REPORTS_DIR = './reports';
// ANSI color codes for beautiful console output
const colors = {
reset: '\x1b[0m',
bright: '\x1b[1m',
dim: '\x1b[2m',
cyan: '\x1b[36m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
magenta: '\x1b[35m',
red: '\x1b[31m',
bgCyan: '\x1b[46m',
bgGreen: '\x1b[42m',
bgYellow: '\x1b[43m',
bgBlue: '\x1b[44m',
};
// Heavy dependencies to test with
const HEAVY_DEPS = [
'@emotion/react',
'@emotion/styled',
'@mui/material',
'@mui/icons-material',
'lodash',
'moment',
'axios',
'react-query',
'd3',
'chart.js',
'react-chartjs-2',
'formik',
'yup',
'date-fns',
'ramda',
'uuid',
'clsx',
'framer-motion',
'react-hook-form',
'zod'
];
function log(message) {
console.log(`[BENCHMARK] ${message}`);
}
function execCommand(command, cwd = process.cwd()) {
log(`Executing: ${command}`);
try {
execSync(command, { cwd, stdio: 'inherit' });
} catch (error) {
log(`Error executing command: ${command}`);
throw error;
}
}
function getDirectorySize(dirPath) {
try {
const output = execSync(`du -sk "${dirPath}"`, { encoding: 'utf8' });
const sizeInKB = parseInt(output.split('\t')[0]);
return sizeInKB;
} catch (error) {
log(`Error getting size for ${dirPath}`);
return 0;
}
}
function formatSize(sizeInKB) {
if (sizeInKB < 1024) {
return `${sizeInKB} KB`;
} else if (sizeInKB < 1024 * 1024) {
return `${(sizeInKB / 1024).toFixed(2)} MB`;
} else {
return `${(sizeInKB / (1024 * 1024)).toFixed(2)} GB`;
}
}
function cleanTempFolder() {
log('Cleaning temp folder...');
if (existsSync(TEMP_DIR)) {
rmSync(TEMP_DIR, { recursive: true, force: true });
}
mkdirSync(TEMP_DIR, { recursive: true });
}
function createNextApp(appName, appPath) {
log(`Creating Next.js app: ${appName}`);
execCommand(
`bunx create-next-app@latest ${appName} --ts --tailwind --app --no-src-dir --import-alias "@/*" --use-bun --no-git`,
TEMP_DIR
);
}
function configureStandaloneMode(appPath) {
log(`Configuring standalone mode for ${appPath}`);
const configPath = join(appPath, 'next.config.ts');
const standaloneConfig = `import type { NextConfig } from "next";
const nextConfig: NextConfig = {
output: 'standalone',
};
export default nextConfig;
`;
writeFileSync(configPath, standaloneConfig);
}
function installHeavyDeps(appPath) {
log(`Installing heavy dependencies in ${appPath}`);
const depsString = HEAVY_DEPS.join(' ');
execCommand(`bun add ${depsString}`, appPath);
}
function buildApp(appPath, appName) {
log(`Building ${appName}...`);
execCommand('bun run build', appPath);
}
function measureAppSizes(appPath, appName, isStandalone) {
const dotNextPath = join(appPath, '.next');
const dotNextSize = getDirectorySize(dotNextPath);
let deploymentSize = 0;
let nodeModulesSize = 0;
if (isStandalone) {
const standalonePath = join(dotNextPath, 'standalone');
if (existsSync(standalonePath)) {
deploymentSize = getDirectorySize(standalonePath);
}
} else {
// Default mode needs .next + node_modules
const nodeModulesPath = join(appPath, 'node_modules');
if (existsSync(nodeModulesPath)) {
nodeModulesSize = getDirectorySize(nodeModulesPath);
}
deploymentSize = dotNextSize + nodeModulesSize;
}
return {
appName,
dotNextSize,
nodeModulesSize: isStandalone ? null : nodeModulesSize,
deploymentSize,
dotNextSizeFormatted: formatSize(dotNextSize),
nodeModulesSizeFormatted: isStandalone ? 'N/A' : formatSize(nodeModulesSize),
deploymentSizeFormatted: formatSize(deploymentSize)
};
}
function generateReport(results) {
log('Generating report...');
if (!existsSync(REPORTS_DIR)) {
mkdirSync(REPORTS_DIR, { recursive: true });
}
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const reportPath = join(REPORTS_DIR, `${timestamp}.txt`);
let report = '='.repeat(80) + '\n';
report += 'Next.js Output Mode Benchmark Report\n';
report += '='.repeat(80) + '\n\n';
report += `Generated: ${new Date().toISOString()}\n\n`;
results.forEach((result, index) => {
report += `${index + 1}. ${result.appName}\n`;
report += '-'.repeat(80) + '\n';
report += ` .next size: ${result.dotNextSizeFormatted}\n`;
report += ` node_modules size: ${result.nodeModulesSizeFormatted}\n`;
report += ` Total deployment size: ${result.deploymentSizeFormatted}\n`;
report += '\n';
});
report += '='.repeat(80) + '\n';
report += 'Summary\n';
report += '='.repeat(80) + '\n\n';
const noDepsDefault = results[0];
const noDepsStandalone = results[1];
const heavyDepsDefault = results[2];
const heavyDepsStandalone = results[3];
report += `No Deps - Default vs Standalone:\n`;
report += ` Default (.next + node_modules): ${noDepsDefault.deploymentSizeFormatted}\n`;
report += ` Standalone: ${noDepsStandalone.deploymentSizeFormatted}\n`;
report += ` Difference: ${formatSize(noDepsStandalone.deploymentSize - noDepsDefault.deploymentSize)}\n\n`;
report += `Heavy Deps - Default vs Standalone:\n`;
report += ` Default (.next + node_modules): ${heavyDepsDefault.deploymentSizeFormatted}\n`;
report += ` Standalone: ${heavyDepsStandalone.deploymentSizeFormatted}\n`;
report += ` Difference: ${formatSize(heavyDepsStandalone.deploymentSize - heavyDepsDefault.deploymentSize)}\n\n`;
report += `Impact of Dependencies:\n`;
report += ` Default mode: ${formatSize(heavyDepsDefault.deploymentSize - noDepsDefault.deploymentSize)} increase\n`;
report += ` Standalone mode: ${formatSize(heavyDepsStandalone.deploymentSize - noDepsStandalone.deploymentSize)} increase\n\n`;
writeFileSync(reportPath, report);
log(`Report saved to: ${reportPath}`);
// Print beautiful console output
printBeautifulReport(results, reportPath);
}
function printBeautifulReport(results, reportPath) {
const noDepsDefault = results[0];
const noDepsStandalone = results[1];
const heavyDepsDefault = results[2];
const heavyDepsStandalone = results[3];
console.log('\n');
console.log(colors.bright + colors.cyan + '╔═══════════════════════════════════════════════════════════════════════════════╗' + colors.reset);
console.log(colors.bright + colors.cyan + '║' + colors.reset + colors.bright + ' 📊 Next.js Output Mode Benchmark Results ' + colors.cyan + '║' + colors.reset);
console.log(colors.bright + colors.cyan + '╚═══════════════════════════════════════════════════════════════════════════════╝' + colors.reset);
console.log('');
// Individual results
results.forEach((result, index) => {
const emoji = result.appName.includes('standalone') ? '📦' : '📁';
const modeColor = result.appName.includes('standalone') ? colors.green : colors.yellow;
console.log(colors.bright + `${emoji} ${index + 1}. ${result.appName}` + colors.reset);
console.log(colors.dim + ' ───────────────────────────────────────────────────────────────────────────' + colors.reset);
console.log(` ${colors.blue}•${colors.reset} .next size: ${colors.bright}${result.dotNextSizeFormatted}${colors.reset}`);
console.log(` ${colors.blue}•${colors.reset} node_modules: ${colors.bright}${result.nodeModulesSizeFormatted}${colors.reset}`);
console.log(` ${colors.blue}•${colors.reset} ${modeColor}Total deployment: ${colors.bright}${result.deploymentSizeFormatted}${colors.reset}`);
console.log('');
});
console.log(colors.bright + colors.magenta + '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━' + colors.reset);
console.log(colors.bright + colors.magenta + ' 📈 Summary & Comparisons' + colors.reset);
console.log(colors.bright + colors.magenta + '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━' + colors.reset);
console.log('');
// No Deps Comparison
const noDepsChange = noDepsStandalone.deploymentSize - noDepsDefault.deploymentSize;
const noDepsArrow = noDepsChange > 0 ? '📈' : '📉';
const noDepsColor = noDepsChange > 0 ? colors.red : colors.green;
console.log(colors.bright + ' 🔹 No Dependencies - Default vs Standalone' + colors.reset);
console.log(` Default: ${colors.yellow}${noDepsDefault.deploymentSizeFormatted}${colors.reset} ${colors.dim}(.next + node_modules)${colors.reset}`);
console.log(` Standalone: ${colors.green}${noDepsStandalone.deploymentSizeFormatted}${colors.reset}`);
console.log(` ${noDepsArrow} Difference: ${noDepsColor}${formatSize(Math.abs(noDepsChange))}${colors.reset} ${noDepsChange > 0 ? 'larger' : 'smaller'}`);
console.log('');
// Heavy Deps Comparison
const heavyDepsChange = heavyDepsStandalone.deploymentSize - heavyDepsDefault.deploymentSize;
const heavyDepsArrow = heavyDepsChange > 0 ? '📈' : '📉';
const heavyDepsColor = heavyDepsChange > 0 ? colors.red : colors.green;
console.log(colors.bright + ' 🔹 Heavy Dependencies - Default vs Standalone' + colors.reset);
console.log(` Default: ${colors.yellow}${heavyDepsDefault.deploymentSizeFormatted}${colors.reset} ${colors.dim}(.next + node_modules)${colors.reset}`);
console.log(` Standalone: ${colors.green}${heavyDepsStandalone.deploymentSizeFormatted}${colors.reset}`);
console.log(` ${heavyDepsArrow} Difference: ${heavyDepsColor}${formatSize(Math.abs(heavyDepsChange))}${colors.reset} ${heavyDepsChange > 0 ? 'larger' : 'smaller'}`);
console.log('');
// Impact of Dependencies
const defaultIncrease = heavyDepsDefault.deploymentSize - noDepsDefault.deploymentSize;
const standaloneIncrease = heavyDepsStandalone.deploymentSize - noDepsStandalone.deploymentSize;
console.log(colors.bright + ' 🔹 Impact of Heavy Dependencies' + colors.reset);
console.log(` Default mode: ${colors.yellow}+${formatSize(defaultIncrease)}${colors.reset} ${colors.dim}(${((defaultIncrease/noDepsDefault.deploymentSize)*100).toFixed(1)}% increase)${colors.reset}`);
console.log(` Standalone mode: ${colors.green}+${formatSize(standaloneIncrease)}${colors.reset} ${colors.dim}(${((standaloneIncrease/noDepsStandalone.deploymentSize)*100).toFixed(1)}% increase)${colors.reset}`);
console.log('');
console.log(colors.dim + ' 💾 Full report saved to: ' + colors.cyan + reportPath + colors.reset);
console.log('');
}
async function runBenchmark() {
console.log('\n' + colors.bright + colors.cyan + '╔═══════════════════════════════════════════════════════════════════════════════╗' + colors.reset);
console.log(colors.bright + colors.cyan + '║' + colors.reset + colors.bright + ' 🚀 Starting Next.js Output Mode Benchmark ' + colors.cyan + '║' + colors.reset);
console.log(colors.bright + colors.cyan + '╚═══════════════════════════════════════════════════════════════════════════════╝' + colors.reset);
// Clean temp folder
cleanTempFolder();
const apps = [
{ name: 'no-deps-default', hasHeavyDeps: false, isStandalone: false },
{ name: 'no-deps-standalone', hasHeavyDeps: false, isStandalone: true },
{ name: 'heavy-deps-default', hasHeavyDeps: true, isStandalone: false },
{ name: 'heavy-deps-standalone', hasHeavyDeps: true, isStandalone: true }
];
const results = [];
for (const app of apps) {
console.log('\n' + colors.bright + colors.cyan + '═'.repeat(80) + colors.reset);
console.log(colors.bright + colors.yellow + `⚙️ Processing: ${app.name}` + colors.reset);
console.log(colors.cyan + '═'.repeat(80) + colors.reset);
const appPath = join(TEMP_DIR, app.name);
// Create app
createNextApp(app.name, appPath);
// Configure standalone mode if needed
if (app.isStandalone) {
configureStandaloneMode(appPath);
}
// Install heavy deps if needed
if (app.hasHeavyDeps) {
installHeavyDeps(appPath);
}
// Build app
buildApp(appPath, app.name);
// Measure sizes
const sizes = measureAppSizes(appPath, app.name, app.isStandalone);
results.push(sizes);
log(`${app.name} - Deployment size: ${sizes.deploymentSizeFormatted}`);
if (!app.isStandalone) {
log(` (.next: ${sizes.dotNextSizeFormatted} + node_modules: ${sizes.nodeModulesSizeFormatted})`);
}
}
// Generate report
generateReport(results);
console.log(colors.bright + colors.green + '✅ Benchmark completed successfully!' + colors.reset);
}
// Run the benchmark
runBenchmark().catch((error) => {
console.error('Benchmark failed:', error);
process.exit(1);
});