When building modern web applications, constants play a huge role — API URLs, timeout values, error messages, routes, and more. But how you export and import constants can affect not only maintainability but also performance and bundle size.
In this post, we’ll explore the different approaches to managing constants in JavaScript/TypeScript projects, compare their pros and cons, and decide which is best for speed and optimization.
Option 1: Separate Exports
// constants.ts
export const API_URL = "https://example.com/api";
export const TIMEOUT = 5000;
export const MAX_RETRIES = 3;
Usage:
import { API_URL, TIMEOUT } from "./constants";
Pros:
Tree-shaking friendly → only what you import gets bundled.
Cleaner auto-imports in IDEs.
No runtime overhead.
Cons:
- File can look cluttered with many constants.
Option 2: Grouped in a Single Object
// constants.ts
const CONSTANTS = {
API_URL: "https://example.com/api",
TIMEOUT: 5000,
MAX_RETRIES: 3,
};
export default CONSTANTS;
Usage:
import CONSTANTS from "./constants";
console.log(CONSTANTS.API_URL);
Pros:
Everything under one namespace.
Easy to pass around as a single object.
Cons:
Loses tree-shaking benefits → entire object is included even if you use just one constant.
Slight runtime overhead (property lookups).
Option 3: Group by Domain
// constants.ts
export const API = {
BASE_URL: "https://example.com/api",
TIMEOUT: 5000,
};
export const APP = {
NAME: "MyApp",
VERSION: "1.0.0",
};
Usage:
import { API, APP } from "./constants";
console.log(API.BASE_URL);
console.log(APP.NAME);
Pros:
- Logical grouping (API, APP, UI, Errors, etc.).
- Still tree-shakeable (you can import only what you need).
- Clean and maintainable for larger teams.
Cons:
- Slightly more verbose than flat exports.
⚡ Optimization & Performance:
Separate exports (Option 1) → Fastest and most optimised for bundle size, because tree-shaking works perfectly.
Grouped object (Option 2) → Worst for performance in large apps, since bundlers include the whole object.
Grouped by domain (Option 3) → Best of both worlds: keeps code organized and still benefits from tree-shaking.
👉 Rule of Thumb:
- Use Option 1 for small projects.
- Use Option 3 for scalable/large apps.
- Avoid dumping everything into a single CONSTANTS object unless you have a strong reason.
Suggested Folder Structure for Constants in React + TypeScript
src/
constants/
api.ts // API endpoints, timeouts
app.ts // App name, version
routes.ts // Route paths
ui.ts // Colors, labels, breakpoints
index.ts // Barrel file (optional)
This keeps constants modular and easy to maintain while ensuring fast loading times.
What about you? How do you organise constants in your projects? Do you prefer flat exports or grouped objects?
Top comments (0)