惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

GbyAI
GbyAI
Simon Willison's Weblog
Simon Willison's Weblog
Microsoft Security Blog
Microsoft Security Blog
Y
Y Combinator Blog
The GitHub Blog
The GitHub Blog
Engineering at Meta
Engineering at Meta
F
Fortinet All Blogs
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
A
About on SuperTechFans
Last Week in AI
Last Week in AI
月光博客
月光博客
有赞技术团队
有赞技术团队
P
Proofpoint News Feed
MyScale Blog
MyScale Blog
Martin Fowler
Martin Fowler
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
C
Check Point Blog
U
Unit 42
The Register - Security
The Register - Security
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Hugging Face - Blog
Hugging Face - Blog
阮一峰的网络日志
阮一峰的网络日志
V
Visual Studio Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
D
DataBreaches.Net
WordPress大学
WordPress大学
aimingoo的专栏
aimingoo的专栏
H
Hacker News: Front Page
Recent Announcements
Recent Announcements
C
CXSECURITY Database RSS Feed - CXSecurity.com
Latest news
Latest news
小众软件
小众软件
P
Palo Alto Networks Blog
PCI Perspectives
PCI Perspectives
Security Latest
Security Latest
S
Secure Thoughts
Scott Helme
Scott Helme
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Threat Research - Cisco Blogs
P
Proofpoint News Feed
M
MIT News - Artificial intelligence
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Google DeepMind News
Google DeepMind News
Recorded Future
Recorded Future
O
OpenAI News
S
Securelist
云风的 BLOG
云风的 BLOG
H
Help Net Security
T
Troy Hunt's Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
What I learned refactoring a codebase with a 7,558-line constants file"
Raviraj Jariwala · 2026-06-21 · via DEV Community

If you've ever opened a file to fix a bug and spent forty minutes just figuring out where the bug lives, this post is for you.

Not because the bug was hard. Because the code had no home.

I've been the sole frontend developer on a sports data platform serving 5+ professional sports clubs. I've worked on this codebase for a few years now, across everything on the frontend — auth flows, build configuration, product features, UI design implementation. When I joined, there were other developers on the team. By the time this refactor started, it was just me.

One of the things I was working with was a file called constant.js with 7,558 lines in it. That number tells you everything you need to know about the state of things.

This is what I did about it, the decisions I made along the way, and what I'd share with anyone facing something similar.

TL;DR: I restructured a 6-product React/Gatsby codebase — 1,100+ files, a 7,558-line constants file, 30-minute builds — into a clean module architecture, fixed two auth bugs affecting real users, and shipped the whole thing without pausing feature delivery.


How codebases get this way

It's worth starting here because I think developers are too quick to blame the people who came before them.

Nobody writes a 7,558-line constants file on purpose.

It starts as a place to put a few shared values. Then one developer adds a constant. Another adds five more. A deadline hits, someone adds twenty at the bottom and ships. Nobody sounds an alarm when a constants file hits 500 lines. Or 1,000. Over years, across multiple developers with different styles, that file becomes something nobody fully understands and everyone is afraid to touch.

That's exactly what happened here.

The platform is a React + Gatsby SaaS app for professional sports organisations. 6 products in one codebase: broadcast analytics, social media tracking, news sentiment, customer intelligence, deal management, revenue forecasting.

When the project started, the team was moving fast on an early-stage product. That's the right call at that stage. You ship, you figure out architecture later.

The problem is "later" kept getting pushed back. By the time I joined, there were a few developers' worth of different coding styles layered on top of each other with no consistent structure.

Everything lived in src/components/ and src/components/pages/. No grouping by product, no grouping by feature. Just files, alphabetically, forever.

And honestly? I followed the same pattern when I joined. You do. You're onboarding into an existing codebase, you match what's already there.

Then the product matured, the client base grew, and what used to be manageable became painful to work in every single day.


What had actually accumulated

Here's the concrete picture. Before any refactoring, the codebase had:

  • constant.js with 7,558 lines, a single file holding every constant the app had ever needed
  • utils.js with 1,115 lines, every helper function all in one place
  • src/components/ with 1,100+ files, no grouping by product or feature
  • 3 unused npm packages still being compiled on every build (@material-ui/core, @material-ui/pickers, apollo-boost)
  • 2 login bugs affecting real users
  • 30+ minute build times on every deploy

Those two login bugs are worth explaining because they were the most user-facing pain.

The first: after your first login, changing the URL from the address bar logged you out. The post-login redirect logic was conflicting with the router state, and navigating away triggered it.

The second: random mid-session logouts. Picture a club analyst mid-presentation, pulling up a live report, and suddenly staring at the login screen. The cause was the idle timer living in component state. Every re-render was resetting it, creating a race condition that eventually fired the logout.

And on top of all this, there was the UI situation.

Some clients were still on the old version. Others had been migrated to the new one. So at any point in time there were three things running:

  • The legacy UI (still live for some clients)
  • The new UI (live for others, actively getting features)
  • A refactoring branch sitting on top of the new UI

Three states of the same codebase. Simultaneously. Picture trying to hold all three clearly in your head every morning before writing a single line of code. New features couldn't pause. Clubs were using this every day.


The call that started the refactor

I had a conversation with the client and laid it out plainly.

The codebase was slowing everything down. Debugging was slow, builds were slow, adding features was getting harder because nothing had a clear home. The ask was simple: let me restructure while still delivering features. No freeze, no "we'll pause and clean up."

They agreed. And then came the harder part: figuring out how to actually do it.


The approach

The temptation with a refactor like this is to fix everything in one big branch. I considered it. It would have been a mistake. It ends in a merge conflict nightmare that never ships.

The constraint here, that features couldn't pause, was actually a gift. It forced the refactor into pieces small enough to be independently merged. One product per PR.

Discover first, then Social, News, Broadcast, Deal Management, Media Hub. Six PRs, each self-contained, each mergeable without the others being finished.

But before moving a single file, the target structure needed to be clear.

Picture opening your editor on the old codebase and seeing this:

Before:

src/
  components/          (1,100+ files, no product grouping)
  components/pages/    (same problem)
  utils/
    constant.js        (7,558 lines)
    utils.js           (1,115 lines)

No labels. No ownership. Every file looks the same regardless of which of the 6 products it belongs to.

Here's what the same codebase looks like after:

After:

src/
  core/                shared across 2+ products
    ui/                reusable UI components
    utils/             split by domain (dates, numbers, charts)
    constants/         split by domain
    hooks/
    services/
    auth/
    features/          global features with their own API calls
  modules/
    airwave/           broadcast analytics
    reach/             social media tracking
    headlines/         news sentiment
    compass/           customer intelligence
    pipeline/          deal management
    studio/            media hub

You can see at a glance which product a file belongs to. You can see what's shared and what isn't.

The rule for src/core/ is simple: if more than one product needs it, it lives here. Nothing product-specific.

The rule for src/modules/{name}/ is visual: the folder structure mirrors the URL. If the route is /app/airwave/insights/overview, the file lives at src/modules/airwave/pages/insights/Overview/. You read the URL, you know exactly where to look.

src/core/features/ is for global features that span products or don't belong to any one of them: things with their own API calls, side effects, and state.

The last piece before starting was adding path aliases to jsconfig.json: @core/*, @modules/*, and product-specific aliases for the most complex ones.

This sounds small. It's probably the highest-leverage change in the whole refactor. No more ../../../components/something. Every import tells you where the file lives.


The mechanics of moving 1,100+ files

This is where things actually go right or wrong, so it's worth being specific.

Step one: import conversion.

I wrote a script to convert relative imports to absolute imports using the new path aliases. The important thing was running it one feature folder at a time, not across the whole codebase in a single pass.

If something broke, the blast radius was one feature. Fix it, verify, move to the next folder. Simple but it saved a lot of pain.

Step two: file moves.

VS Code's built-in file move handles most import updates automatically. For everything else, git mv in the terminal.

This matters more than it sounds. git mv tells git the file moved rather than treating it as a deletion and a new file. After the migration, git blame and git log --follow still work. You can still trace why a line was written two years ago by someone no longer on the team.

In a codebase without a test suite, that history is one of the few tools you have for understanding why something was done a certain way. Worth protecting.

What each PR looked like:

Every product PR ended the same way. The last few commits were always: organise product-specific constants into the module, pull anything shared into src/core/, and break down any file over 500 lines into smaller, readable pieces.

Not perfectly small. Just below 500 and coherent enough to open without getting lost.

The hardest part:

The deal management module was the most difficult. It felt like rearranging a room while someone was still living in it. That product was being actively changed based on client feedback at the same time I was restructuring its files. Every day there was a new conflict to resolve between the refactoring branch and what was landing on the main branch.

Honestly, I thought about skipping the deal management module entirely and coming back to it later. Instead I skipped individual files within it when the conflict risk wasn't worth it, noted them, and moved on. A partial migration that ships cleanly beats a complete one that breaks something in production.


Fixing the bugs

Login bug one (URL change logging users out):

The post-login redirect logic was conflicting with the router state. Navigating via the address bar after first login triggered the logout flow.

Fixed by simplifying: always redirect to the home route on login, then let the router handle navigation from there. One clear responsibility, no conflicts.

Login bug two (mid-session logouts):

The idle timer moved from component state to useRef. No more re-renders, no more race condition.

User data fetching changed from sequential to concurrent. And localStorage cleanup on logout was scoped to only the specific keys that needed clearing, instead of wiping everything.

The build time:

Removing @material-ui/core, @material-ui/pickers, and apollo-boost from package.json was the bulk of the improvement. They were being compiled on every build and hadn't been used in a long time.


What changed

  • 3,900+ files touched across 74 commits
  • Around 18,000 net lines removed (284k deleted, 265k added)
  • Build time: 30+ minutes → 17-18 minutes, just from removing dead weight
  • Both login bugs resolved, no reports since
  • All 6 products with their own clearly bounded home in the codebase
  • No client disruption throughout, legacy and new UI both stayed live

What I'd do differently

Set up the structure before anyone writes code against the old one.

The hardest part of this refactor wasn't the architecture decisions. It was migrating files while new code was still landing in the old locations. If the module structure and path aliases exist from the start, people move their own code naturally. Running a large migration alongside active development adds friction that didn't need to be there.

Add ESLint rules early.

Right now the conventions live in documentation. That works while I'm the only developer. But the moment anyone else touches the codebase under pressure, the first thing they'll do is import from the familiar old path.

A linting rule that fails the build enforces the architecture without relying on anyone's memory. You set it once, it quietly holds the line for you after that. Two lines of config, permanent guardrails.


The thing worth remembering

Messy codebases aren't created by bad developers.

They're created by good developers solving the right problems at the right time, without the bandwidth to also clean up behind themselves. The mess accumulates quietly, one reasonable decision at a time, until one day it feels heavy enough to slow everything down.

The lesson isn't to plan everything perfectly from day one. That's not realistic when a product is still finding its shape.

The lesson is to recognise when the codebase needs to grow up along with the product, and to make that investment before the cost gets too high.

Looking back, the hardest part wasn't technical. It was doing this alongside active feature delivery without letting either side slip. Almost every win came from removing things, not adding them. The faster build came from deleting dead packages. The auth reliability came from moving a variable to the right place. The debuggability came from splitting nearly 9,000 lines of monolithic files into files that know what they are.

If your codebase feels like this right now, you don't need the perfect plan before you start. Pick one product, one module, one folder. Clean it up. Ship it. Then do the next one.

That's really the whole approach.