Modular Frontend: How to Structure Before Splitting
In this article
This guide explains how to make a frontend codebase modular before you actually split it into separate packages, micro-frontends, or shared libraries. You'll learn to identify boundaries, extract reusable logic, and create a structure that makes the eventual split smooth and safe. This approach reduces merge conflicts, improves testability, and lets multiple teams work in parallel without stepping on each other's toes.
What You'll Need
- Access to the existing frontend codebase (Git repository).
- A code editor or IDE.
- Basic understanding of JavaScript/TypeScript and the framework you use (React, Vue, Angular, etc.).
- Familiarity with your build tool (Webpack, Vite, etc.) and package manager (npm, yarn, pnpm).
- Time to refactor incrementally—do not attempt a big-bang rewrite.
Step-by-Step
- Map the current state. Draw a diagram of your app's pages, components, and shared utilities. Note which parts are reused across multiple features (e.g., a date picker, an API client, a formatting function). Identify areas where code is duplicated or tightly coupled.
- Define clear boundaries. Based on the map, group code into logical domains: e.g., `auth`, `checkout`, `product`, `shared`. Each domain should have a single responsibility. Avoid cross-domain imports where possible—if two domains share a component, it should live in `shared`.
- Create a folder structure that reflects those boundaries. Within your `src` folder, create directories for each domain and a `shared` folder. Move files into these folders, updating imports as you go. This is a physical change, but it's the first step toward modularity.
- Extract shared utilities into a dedicated module. Take functions like date formatting, currency conversion, or API request wrappers and put them in `src/shared/utils`. Export them as named exports. Ensure they are pure (no side effects) so they can be tested independently.
- Create a single entry point for each domain. For each domain folder, add an `index.js` (or `index.ts`) that exports the public API of that domain—the components and functions other parts of the app are allowed to use. This makes the domain's surface area explicit.
- Enforce the boundaries with lint rules. Use ESLint with `import/no-restricted-paths` to prevent imports from one domain into another (except through the index). This catches violations early.
- Decouple state management. If you use Redux, Vuex, or similar, separate the store per domain. Each domain should have its own slice/module, and the root store should simply combine them. This prevents one domain from directly reading another's state.
- Introduce a shared design system (if not already present). Move UI primitives (buttons, inputs, modals) into `src/shared/ui`. Ensure they are styled consistently and have no business logic. This is the foundation for a component library later.
- Write tests for the extracted modules. At minimum, test the shared utilities and the public API of each domain. This gives you confidence that the extraction didn't break behavior.
- Review and iterate. Run your full test suite and manually check key user flows. Look for remaining tight couplings—e.g., a component in `checkout` that directly imports a component from `product`—and refactor them to go through the shared layer or move the component.
Common Mistakes
- Creating circular dependencies. When moving files, it's easy to end up with two modules importing each other. Use a tool like `madge` to detect cycles and break them by moving the shared piece into a lower-level module.
- Over-abstracting too early. Don't create a micro-frontend or a package for every tiny utility. Modularity is about boundaries, not about splitting everything into separate packages. Keep it simple until you actually need to split.
- Ignoring side effects. If a shared utility has a side effect (e.g., writes to localStorage), it becomes harder to test and reuse. Keep side effects at the edge of your app.
- Not updating imports consistently. After moving files, you must update all import paths. Use your IDE's refactoring tools or a codemod to avoid missing any.
- Skipping the index.js pattern. Without a clear public API, other modules might import deep paths, which makes refactoring harder later.
Tips
- Start with the most obvious shared utilities—they give the quickest win.
- Use TypeScript interfaces to define the props of your shared components. This makes the contract explicit.
- Keep the folder structure flat enough to avoid deep nesting; a depth of 2-3 levels is usually fine.
- Automate the import path updates with tools like `eslint-plugin-import` or `ts-morph`.
- Document the boundaries in a README in the `src` folder. Explain what each domain is responsible for and what is forbidden.
- If you plan to split into separate packages later, use a monorepo tool like Lerna or Nx from the start—it makes the transition easier.
Troubleshooting
Problem: The app breaks after moving files.
Check for missing or incorrect import paths. Run your linter and type checker—they will point to the exact file and line. If the error is a circular dependency, use `madge` to visualize the graph and break the cycle by moving the shared code into a new module.
Problem: Tests fail because of missing mocks.
If you moved a module that was previously mocked, your test setup may not find it. Update the mock paths. Also, ensure that your test environment can resolve the new folder structure (e.g., adjust `moduleNameMapper` in Jest).
Problem: Performance degrades after extraction.
This can happen if you accidentally created a large bundle because of circular imports or if you moved code into a module that is loaded on every page. Use your bundler's analysis tool to see what's being included. You may need to use dynamic imports for heavy modules.
Problem: Merge conflicts become worse.
If you are working in a team, coordinate the refactoring. Do it in small, incremental PRs that only move files or only change imports—not both at once. This reduces the chance of conflicts.
Frequently Asked Questions
What is the difference between modular and component-based?
Component-based is about UI reuse; modular is about logical boundaries. A modular frontend can have components, but it also separates concerns like data fetching, state, and utilities into independent modules.
Do I need a monorepo to make my frontend modular?
No. You can achieve modularity with folders and clear boundaries. A monorepo helps when you actually split into multiple packages, but it's not a prerequisite.
How do I convince my team to do this refactoring?
Focus on the pain points: slow builds, merge conflicts, difficulty testing. Show how modularity addresses these. Start with a small, safe extraction and demonstrate the benefit.
Can I use this approach with any framework?
Yes. The principles are framework-agnostic. The folder structure and import rules work the same in React, Vue, Angular, or even vanilla JS.
What if my app is already a mess? Is it too late?
It's never too late. Start by mapping the current state and identifying the most independent piece. Even a small improvement reduces complexity. Do it incrementally.
How long does this refactoring take?
It depends on the size of your codebase. For a medium-sized app, expect a few days to a week of focused work, but you can spread it over several sprints.