Modern JavaScript Modules for React Projects

Learn how JavaScript modules organize React code with named and default exports, practical import patterns, common failure fixes, and build boundary tips.

published: reading time: 8 min read author: Geek Workbench
Quick Summary

JavaScript modules let React projects split components, helpers, and data into files with explicit imports and exports. Named exports make shared APIs easy to see, while default exports suit a file’s main component; import paths still need to match names and casing. This guide also covers circular dependencies, client-side secrets, bundle checks, and debugging failed imports.

Modern JavaScript Modules: Import and Export for React Projects

Introduction

A React app usually starts small. As components and helpers spread across files, modules make ownership and dependencies easier to see.

The examples in this article use ECMAScript Modules (ESM), the module syntax defined by ECMAScript. React projects commonly use ESM imports and exports, with a bundler handling project files for the browser. Node.js also supports CommonJS (require and module.exports); its module mode depends on file extensions, package metadata, and Node’s loading rules. A bundler may add aliases, extension resolution, or transforms that native Node ESM does not provide. For the runtime details here, see the ECMAScript specification and Node.js 22.15 ESM documentation.

For example, a price formatter can live in its own file and be imported by a component that needs it:

// formatPrice.js
export function formatPrice(value) {
  return `$${value.toFixed(2)}`;
}

// ProductCard.jsx
import { formatPrice } from "./formatPrice.js";

Named or default export?

For shared components and utilities, prefer named exports as the project default: import names then match the exported API, which makes refactors and searches easier. Use a default export when the project framework or file convention expects one, and keep that choice consistent within the feature.

A default export represents the file’s primary value. Its importer chooses the local name:

// ProfileCard.jsx
export default function ProfileCard({ name }) {
  return <article>{name}</article>;
}
import ProfileCard from "./ProfileCard.jsx";

Named exports suit files with several values; defaults suit files centered on one component. Pick a convention and use it consistently. JavaScript allows one default export per file and many named exports.

Trade-Off Table

Pattern Import form Useful when Trade-off
Named export import { formatPrice } from "./price.js" A module exposes several values Import name must match, unless aliased
Default export import ProfileCard from "./ProfileCard.jsx" One value is the file’s main purpose Local import name can drift across files

Import within a feature folder

Keep code that changes together in a feature folder, and import from a clear public entry point when that helps callers avoid depending on implementation details:

src/features/cart/
  CartPage.jsx
  CartSummary.jsx
  cartApi.js
  index.js
// src/features/cart/index.js
export { CartPage } from "./CartPage.jsx";
export { CartSummary } from "./CartSummary.jsx";
// A route or parent feature imports the public API.
import { CartPage } from "../features/cart/index.js";

An index.js barrel is useful only if it represents an intentional boundary. It can obscure dependencies or create cycles if it re-exports everything indiscriminately. See component boundaries and project structure for ways to organize feature folders.

Follow the module path

graph LR
  Component[ProductPage.jsx] --> Helper[formatPrice.js]
  Component --> Data[products.js]
  Helper --> Output[Formatted price]
  Data --> Output

A component imports what it needs, and the bundler follows those paths. ESM imports declare dependencies before code runs.

Production Failure Scenarios

A common error is importing a named export as a default, or the reverse. Compare both sides: change import { SaveButton } to import SaveButton only if the source uses export default.

A path typo stops a build. Check the folder and capitalization. An import of saveButton.jsx can fail in Linux CI when the actual file is SaveButton.jsx.

ESM cycles do not always fail, because imports are live bindings. They can fail when a module reads another module’s binding before that binding has been initialized. This compact example creates that temporal-dead-zone error:

// a.js
import { valueB } from "./b.js";
export const valueA = "A";
console.log(valueB);

// b.js
import { valueA } from "./a.js";
export const valueB = valueA + "B"; // ReferenceError during cyclic evaluation

Move shared values or logic into a third module, or defer the read until after initialization. A bundler warning can help locate the cycle, but the exact warning behavior depends on the tool.

Common Pitfalls / Anti-Patterns

  • Mixing named and default import syntax without checking the source declaration.
  • Turning a shared index.js barrel into a dumping ground for unrelated modules, which hides dependency paths.
  • Treating an import as a privacy boundary; browser code and its dependencies can be inspected.

Security and Compliance Notes

Imports define build dependencies, not access control. A secret in a frontend module can ship to the browser, so keep credentials on a server and expose only public configuration. Keep tokens and other secrets out of logs.

Observability Checklist

  • Use the browser console and source maps to trace a failing import.
  • In CI, check a missing-module error for a typo or casing mismatch.
  • Inspect production bundle size when a dependency adds unexpected weight; importing a whole utility library may include unused code.

When to Use / When NOT to Use

Use modules to separate reusable components, hooks, formatters, or data that benefits from a clear owner. Explicit imports make dependencies visible to readers and the bundler.

Keep a tiny one-off script in one file when splitting it would add path hops without clarifying ownership. Avoid creating a module for every constant if it makes related code harder to follow.

Quick Recap Checklist

  • Export named values with export and import them inside braces.
  • Use export default for a file’s primary value; import it without braces.
  • Resolve relative paths from the file doing the import, including correct filename casing.
  • Keep secrets out of client modules and investigate bundle growth at the import boundary.

Interview Questions

1. What is the difference between a named and default export?
A module can expose multiple named exports, which imports reference by name inside braces. It can also expose one default export, which the importer can assign any local name.
2. Why can a module import fail in CI but work locally?
CI often runs on a case-sensitive filesystem. Match the import path exactly to the file’s capitalization and check that the path is relative to the importing module.
3. Why are ESM imports useful to a bundler?
Top-level imports and exports describe dependencies before code runs. A bundler can follow those links, report missing modules, and remove some unused exports during production builds.
4. How do you rename a named import locally?
Use the as keyword inside the braces:
  • import { formatPrice as formatCurrency } from "./price.js"
  • The local name changes; the exported name does not.
5. Can one module have multiple default exports?
No. A module has at most one default export.
  • It may have many named exports.
  • Use named exports when callers need several values from a module.
6. What does a relative import path describe?
It locates a module from the file containing the import.
  • ./ starts in the current directory.
  • ../ moves to its parent directory.
7. What is a circular dependency?
Two or more modules depend on each other in a cycle.
  • The cycle can expose a value before it is initialized.
  • Move shared logic into a third module to break the cycle.
8. Does importing a frontend module keep its values private?
No. Client-side modules and their bundled values can be inspected.
  • Keep credentials on a server.
  • Only expose public configuration to browser code.
9. When is a barrel file useful?
A barrel can provide a clear public entry point for a cohesive module group.
  • Keep its exports related and intentional.
  • Avoid hiding unrelated dependency paths in a catch-all index.
10. What should you check when an import fails only in CI?
Check path spelling, capitalization, and the source file’s export form.
  • Linux CI may use case-sensitive paths.
  • Named and default import syntax must match the declaration.

Further Reading

Conclusion

ESM gives React files a clear way to share components and logic. Match import syntax to the export, keep paths accurate, use a consistent named-export convention for shared modules, and assume client imports may ship to the browser.

Category

Related Posts

Accessible React UI: Semantics, Labels, and Keyboard Use

Build React interfaces with semantic controls, connected labels, visible keyboard focus, and status announcements through practical TypeScript examples.

#react #typescript #accessibility

npm and Package Scripts for React Projects

Learn how npm installs React dependencies, records exact versions in a lockfile, and runs repeatable project scripts with a safer everyday workflow.

#npm #react #javascript

Styling React Components and Importing Assets

Compare plain CSS with CSS modules, then learn how Vite handles imported files and public assets in React projects, with practical code examples.

#react #css #vite