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

推荐订阅源

Microsoft Azure Blog
Microsoft Azure Blog
GbyAI
GbyAI
P
Proofpoint News Feed
Engineering at Meta
Engineering at Meta
Recent Announcements
Recent Announcements
L
LangChain Blog
B
Blog
阮一峰的网络日志
阮一峰的网络日志
Microsoft Security Blog
Microsoft Security Blog
博客园 - 【当耐特】
M
MIT News - Artificial intelligence
D
Docker
WordPress大学
WordPress大学
J
Java Code Geeks
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The GitHub Blog
The GitHub Blog
博客园 - 叶小钗
Last Week in AI
Last Week in AI
Stack Overflow Blog
Stack Overflow Blog
有赞技术团队
有赞技术团队
MyScale Blog
MyScale Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
MongoDB | Blog
MongoDB | Blog
博客园 - Franky

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
JavaScript Modules: Import & Export Explained
Ritam Saha · 2026-04-29 · via DEV Community

The Chaos of Unorganized Code

Imagine you're building a full-stack app - your main.js file have 1,000+ lines. Functions for user authentication, data fetching, and UI utils all mashed together. Debugging? A nightmare! Reusing a helper function in another project? first find that particular helper function, carefully watch its scopes.. and the copy-paste hell. And sharing code with teammates? Forget it! This "spaghetti code problem" plagued early JavaScript, turning simple scripts into unmaintainable monsters as projects grew.

Entry of JavaScript modules: a game-changer for splitting code into different reusable files, organized pieces. No more codes pollution in one file or script tag. Modules let you export what you create and import what you need, making your code cleaner, scalable, and team-friendly. Let's dive in.


Why Modules Are Needed

Before ES6 modules (introduced in 2015), developers relied on hacks like IIFEs (Immediately Invoked Function Expressions) or global variables. These caused issue in code flows and conflicts.

Modules solve this by:

  • Encapsulating code: Variables and functions stay private unless explicitly exported or used in closures.
  • Enabling reuse: Write once, import anywhere.
  • Improving organization: Break apps into logical files (e.g., auth.js, api.js) for better understanding.

They arrived natively in browsers via <script type="module">, no bundlers required initially.

File Dependency Diagram


Exporting Functions or Values

Exporting shares your code with the world. Place export before declarations in your module file.

Named exports (multiple per file):

// mathUtils.js
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;
export const PI = 3.14159;

Enter fullscreen mode Exit fullscreen mode

Default export (only one per file, no name needed):

// user.js
const createUser = (name, email) => ({ name, email });

export default createUser;  // Import it as any name later

Enter fullscreen mode Exit fullscreen mode

Export at the end too:

const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
export { add, subtract };  // Re-export named ones

Enter fullscreen mode Exit fullscreen mode


Importing Modules

To use exports, import them in another file by using relative paths like ./mathUtils.js.

Named imports (match export names):

// main.js
import { add, multiply, PI } from './mathUtils.js';

console.log(add(2, 3));  // 5

Enter fullscreen mode Exit fullscreen mode

Default imports (flexible naming):

// main.js
import createUser from './user.js';  // 'createUser' can be any name

const user = createUser('Ritam', 'ritam@example.com');

Enter fullscreen mode Exit fullscreen mode

Import everything:

import * as math from './mathUtils.js';
math.add(4, 5);

Enter fullscreen mode Exit fullscreen mode

Module Import/Export Flow


Default vs Named Exports

  • Named: Specific, great for multiple exports. Must match names on import. Ideal for utilities: import { logError } from './logger.js';.
  • Default: One per module, import as any name. Perfect for a module's "main" feature: import express from 'express';.

Pro tip: Use named for libraries (predictable API), default for single-purpose modules. Mixing works too!


Benefits of Modular Code

Modules transform maintainability:

  • Easier debugging: Isolate issues to one file.
  • Better collaboration: Teams own modules (e.g., you handle auth, I handle API).
  • Tree-shaking: Unused exports vanish in builds.
  • Scalability: Your portfolio projects grow without chaos—think Node.js backends or React apps.

Conclusion: Level Up Your JS Projects Today

JavaScript modules aren't just syntax—they're the backbone of modern web dev. Ditch the monolith; embrace exports and imports for code that scales with your ambitions. Next time you start a project, ask: "Can this be a module?" Your future self (and interviewers) will thank you.

Grab your editor, refactor a script, and share your wins!