The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Optimize bundle size
Steven Teya290c7a9d0b6
diff --git a/apps/web/next.config.js b/apps/web/next.config.jsindex a3bad8f2b5..10fefa447c 100644--- a/apps/web/next.config.js+++ b/apps/web/next.config.js@@ -1,19 +1,15 @@const { PrismaPlugin } = require("@prisma/nextjs-monorepo-workaround-plugin");const { withAxiom } = require("next-axiom");-const path = require("path");--const REDIRECT_SEGMENTS = [- "pricing",- "blog",- "help",- "changelog",- "tools",- "_static",-];/** @type {import('next').NextConfig} */module.exports = withAxiom({reactStrictMode: false,+ optimizePackageImports: [+ "@dub/email",+ "@dub/ui",+ "@dub/utils",+ "@team-plain/typescript-sdk",+ ],transpilePackages: ["shiki","@dub/prisma",@@ -138,34 +134,6 @@ module.exports = withAxiom({permanent: true,statusCode: 301,},- ...REDIRECT_SEGMENTS.map(- (segment) => (- {- source: `/${segment}`,- has: [- {- type: "host",- value: "dub.sh",- },- ],- destination: `https://dub.co/${segment}`,- permanent: true,- statusCode: 301,- },- {- source: `/${segment}/:path*`,- has: [- {- type: "host",- value: "dub.sh",- },- ],- destination: `https://dub.co/${segment}/:path*`,- permanent: true,- statusCode: 301,- }- ),- ),{source: "/",has: [diff --git a/apps/web/package.json b/apps/web/package.jsonindex fb4de6e6ef..958c9f745e 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -37,8 +37,6 @@"@radix-ui/react-hover-card": "^1.1.1","@react-pdf/renderer": "^4.1.5","@sindresorhus/slugify": "^2.2.1",- "@splinetool/react-spline": "^2.2.6",- "@splinetool/runtime": "^1.2.8","@stripe/stripe-js": "^7.3.1","@tanstack/react-table": "^8.17.3","@team-plain/typescript-sdk": "^5.9.0",@@ -67,7 +65,6 @@"bottleneck": "^2.19.5","buffer-crc32": "0.2.13","cmdk": "^1.1.1",- "cobe": "^0.6.3","concurrently": "^8.0.1","csv-parse": "^5.5.6","date-fns": "^3.6.0",diff --git a/apps/web/scripts/analyze-bundle.ts b/apps/web/scripts/analyze-bundle.tsnew file mode 100644index 0000000000..d91d1fb3cf--- /dev/null+++ b/apps/web/scripts/analyze-bundle.ts@@ -0,0 +1,200 @@+import fs from "fs";+import path from "path";++// Types and interfaces+interface Dependency {+ name: string;+ version: string;+ size: number;+ formattedSize: string;+}++interface PackageGroup {+ group: string;+ packages: Dependency[];+ totalSize: number;+}++interface PackageJson {+ dependencies: Record<string, string>;+ devDependencies: Record<string, string>;+}++// Function to get directory size recursively+function getDirectorySize(dirPath: string): number {+ let totalSize = 0;++ try {+ const items = fs.readdirSync(dirPath);++ for (const item of items) {+ const itemPath = path.join(dirPath, item);+ const stats = fs.statSync(itemPath);++ if (stats.isDirectory()) {+ totalSize += getDirectorySize(itemPath);+ } else {+ totalSize += stats.size;+ }+ }+ } catch (error) {+ // Skip if directory doesn't exist or can't be read+ }++ return totalSize;+}++// Function to format bytes to human readable format+function formatBytes(bytes: number): string {+ if (bytes === 0) return "0 Bytes";++ const k = 1024;+ const sizes = ["Bytes", "KB", "MB", "GB"];+ const i = Math.floor(Math.log(bytes) / Math.log(k));++ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];+}++// Function to get dependencies from package.json+function getDependencies(): Record<string, string> {+ const packageJsonPath = path.join(__dirname, "../package.json");+ const packageJson: PackageJson = JSON.parse(+ fs.readFileSync(packageJsonPath, "utf8"),+ );++ return {+ ...packageJson.dependencies,+ ...packageJson.devDependencies,+ };+}++// Function to analyze dependencies+function analyzeDependencies(): Dependency[] {+ const allDependencies = getDependencies();+ const dependencySizes: Dependency[] = [];+ const nodeModulesPath = path.join(__dirname, "../node_modules");++ for (const [packageName, version] of Object.entries(allDependencies)) {+ const packagePath = path.join(nodeModulesPath, packageName);++ if (fs.existsSync(packagePath)) {+ const size = getDirectorySize(packagePath);+ dependencySizes.push({+ name: packageName,+ version,+ size,+ formattedSize: formatBytes(size),+ });+ }+ }++ // Sort by size (largest first)+ return dependencySizes.sort((a, b) => b.size - a.size);+}++// Function to find duplicate packages+function findDuplicatePackages(dependencySizes: Dependency[]): PackageGroup[] {+ const packageGroups: Record<string, Dependency[]> = {};++ dependencySizes.forEach((dep) => {+ const baseName = dep.name.split("/")[0];+ if (!packageGroups[baseName]) {+ packageGroups[baseName] = [];+ }+ packageGroups[baseName].push(dep);+ });++ return Object.entries(packageGroups)+ .filter(([, packages]) => packages.length > 1)+ .map(([name, packages]) => ({+ group: name,+ packages,+ totalSize: packages.reduce((sum, pkg) => sum + pkg.size, 0),+ }));+}++// Function to print analysis results+function printAnalysis(dependencySizes: Dependency[]): void {+ console.log("π Analyzing bundle size...\n");++ // Print top 20 largest dependencies+ console.log("π¦ Top 20 Largest Dependencies:\n");+ console.log("Package Name".padEnd(40) + "Version".padEnd(20) + "Size");+ console.log("-".repeat(80));++ dependencySizes.slice(0, 20).forEach((dep, index) => {+ const rank = (index + 1).toString().padStart(2);+ console.log(+ `${rank}. ${dep.name.padEnd(37)} ${dep.version.padEnd(20)} ${dep.formattedSize}`,+ );+ });++ // Calculate totals+ const totalSize = dependencySizes.reduce((sum, dep) => sum + dep.size, 0);+ const top20Size = dependencySizes+ .slice(0, 20)+ .reduce((sum, dep) => sum + dep.size, 0);++ console.log("\n" + "=".repeat(80));+ console.log(`Total size of all dependencies: ${formatBytes(totalSize)}`);+ console.log(`Top 20 dependencies size: ${formatBytes(top20Size)}`);+ console.log(+ `Top 20 represent ${((top20Size / totalSize) * 100).toFixed(1)}% of total size`,+ );+}++// Function to print optimization opportunities+function printOptimizationOpportunities(dependencySizes: Dependency[]): void {+ console.log("\nπ― Potential Optimization Opportunities:\n");++ // Find large packages (>1MB)+ const largePackages = dependencySizes.filter((dep) => dep.size > 1024 * 1024);++ // Find duplicate packages+ const duplicatePackages = findDuplicatePackages(dependencySizes);++ if (duplicatePackages.length > 0) {+ console.log("π Potential duplicate/similar packages:");+ duplicatePackages.forEach((group) => {+ console.log(` ${group.group}:`);+ group.packages.forEach((pkg) => {+ console.log(` - ${pkg.name}@${pkg.version}: ${pkg.formattedSize}`);+ });+ console.log(` Total: ${formatBytes(group.totalSize)}\n`);+ });+ }++ // Check for very large packages (>5MB)+ const veryLargePackages = dependencySizes.filter(+ (dep) => dep.size > 5 * 1024 * 1024,+ );++ if (veryLargePackages.length > 0) {+ console.log("β οΈ Very large packages (>5MB) - consider alternatives:");+ veryLargePackages.forEach((dep) => {+ console.log(` - ${dep.name}@${dep.version}: ${dep.formattedSize}`);+ });+ }++ console.log("\nπ‘ Tips for reducing bundle size:");+ console.log("1. Use dynamic imports for large libraries");+ console.log("2. Consider tree-shaking friendly alternatives");+ console.log("3. Use bundle analyzer to identify unused code");+ console.log("4. Consider code splitting for large components");+ console.log("5. Remove unused dependencies");+}++// Main function+function main(): void {+ try {+ const dependencySizes = analyzeDependencies();+ printAnalysis(dependencySizes);+ printOptimizationOpportunities(dependencySizes);+ } catch (error) {+ console.error("β Error analyzing bundle:", error);+ process.exit(1);+ }+}++// Run the analysis+main();diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 28739ccff3..299b3affa6 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -100,12 +100,6 @@ importers:'@sindresorhus/slugify':specifier: ^2.2.1version: 2.2.1- '@splinetool/react-spline':- specifier: ^2.2.6- version: 2.2.6(@splinetool/[email protected])([email protected]([email protected]))([email protected])- '@splinetool/runtime':- specifier: ^1.2.8- version: 1.2.8'@stripe/stripe-js':specifier: ^7.3.1version: 7.3.1@@ -190,9 +184,6 @@ importers:cmdk:specifier: ^1.1.1version: 1.1.1(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])- cobe:- specifier: ^0.6.3- version: 0.6.3concurrently:specifier: ^8.0.1version: 8.0.1@@ -4907,16 +4898,6 @@ packages:'@socket.io/[email protected]':resolution: {integrity: sha512-+9jVqKhRSpsc591z5vX+X5Yyw+he/HCB4iQ/RYxw35CEPaY1gnsNE43nf9n9AaYjAQrTiI/mOwKUKdUs9vf7Xg==}- '@splinetool/[email protected]':- resolution: {integrity: sha512-y9L2VEbnC6FNZZu8XMmWM9YTTTWal6kJVfP05Amf0QqDNzCSumKsJxZyGUODvuCmiAvy0PfIfEsiVKnSxvhsDw==}- peerDependencies:- '@splinetool/runtime': '*'- react: '>=17.0.0'- react-dom: '>=17.0.0'-- '@splinetool/[email protected]':- resolution: {integrity: sha512-P6laYT0F+XeFQm1pq1taKBD0f2HPoy9YcjOxXglfMhUH9/Y/fLDTlZE4BVS2DDVmUB8eJrU5gY4Vb5pDBMO7IQ==}-'@sqltools/[email protected]':resolution: {integrity: sha512-Uy0+khmZqUrUGm5dmMqVlnvufZRSK0FbYzVgp0UMstm+F5+W2/jnEEQyc9vo1ZR/E5ZI/B1WjjoTqBqwJL6Krw==}@@ -6304,9 +6285,6 @@ packages:resolution: {integrity: sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==}engines: {iojs: '>= 1.0.0', node: '>= 0.12.0'}- resolution: {integrity: sha512-WHr7X4o1ym94GZ96h7b1pNemZJacbOzd02dZtnVwuC4oWBaLg96PBmp2rIS1SAhUDhhC/QyS9WEqkpZIs/ZBTg==}-resolution: {integrity: sha512-lHl4d5/ONEbLlJvaJNtsF/Lz+WvB07u2ycqTYbdrq7UypDXailES4valYb2eWiJFxZlVmpGekfqoxQhzyFdT4Q==}@@ -9429,10 +9407,6 @@ packages:resolution: {integrity: sha512-IF4PcGgzAr6XXSff26Sk/+P4KZFJVuHAJZj3wgO3vX2bMdNVp/QXTP3P7CEm9V1IdG8lDLY3HhiqpsE/nOwpPw==}engines: {node: ^10.13.0 || >=12.0.0}- resolution: {integrity: sha512-cMtCyuJmTx/bg2HCpHo3ZLeF7FZnBOapLqZHr2AlLeJ5Ul0Zu2mUJJz051Fdwu/Et2YW04ZD+TtU+gVy0ACNCA==}- engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}-resolution: {integrity: sha512-ikqdkGAAyf/X/gPhXGvfgAytDZtDbr+bkNUJ0N9h5MI/dmdgCs3l6hoHrcUv41sRKew3jIwrp4qQDXiK99Utww==}engines: {node: '>= 0.8'}@@ -9645,9 +9619,6 @@ packages:resolution: {integrity: sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==}- resolution: {integrity: sha512-7h9/fjPD3qNlgggzm88cY58l9sudZ6Ey+UmZsizfhtawO6E3srZQXywaNm2lBwT72TbpHYRPy7ytIHeBUD/G0A==}-resolution: {integrity: sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==}@@ -10036,9 +10007,6 @@ packages:'@types/react': '>=18'react: '>=18'- resolution: {integrity: sha512-jLQXJ/URln51zskhgppGJ2ub7b2WFKGq3cl3NYKtlHoTG+dN2q7EzWrn3hN3EgPsTMvpR9tpq5ijdp7YwFZkag==}-resolution: {integrity: sha512-oIewslu5DBwOmo7x5rdzZlZXCqDIna0R4dUwVpfmVteORYLr4yaZo5wQnMeR+H7x54GaMhmgeqp0ZpULtulJFg==}engines: {node: '>=16'}@@ -10470,9 +10438,6 @@ packages:resolution: {integrity: sha512-5TF+l7p4+OsnP8BCCvSyZiSPc4x4//p5uPwK8TCnVPJYRmU2aYKMpOXvw8zM5a5JvuuCGN1jmsMwuU2W02ukfA==}- resolution: {integrity: sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==}-resolution: {integrity: sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==}hasBin: true@@ -17184,19 +17149,6 @@ snapshots:'@socket.io/[email protected]': {}- '@splinetool/[email protected](@splinetool/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@splinetool/runtime': 1.2.8- lodash.debounce: 4.0.8- react: 18.2.0- react-dom: 18.2.0([email protected])- react-merge-refs: 2.1.1-- '@splinetool/[email protected]':- dependencies:- on-change: 4.0.2- semver-compare: 1.0.0-'@sqltools/[email protected]': {}'@stripe/[email protected]': {}@@ -18856,10 +18808,6 @@ snapshots:- dependencies:- phenomenon: 1.6.0-@@ -22871,8 +22819,6 @@ snapshots:- [email protected]: {}-dependencies:ee-first: 1.1.1@@ -23107,8 +23053,6 @@ snapshots:dependencies:split2: 4.2.0- [email protected]: {}-@@ -23553,8 +23497,6 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected]: {}-[email protected](@babel/[email protected])(@babel/[email protected](@babel/[email protected]))([email protected])([email protected]):dependencies:'@jest/create-cache-key-function': 29.7.0@@ -24188,8 +24130,6 @@ snapshots:dependencies:parseley: 0.12.1- [email protected]: {}-