When one file can't hold it anymore: modules, import, and export, explained plainly
One main.js past six hundred lines, menu, orders, checkout, and printing squeezed together. This guide follows MDN's JavaScript modules, import, and export references: scripts vs modules, named and default exports, renaming with as, namespace imports, barrel modules, side-effect and JSON imports, hoisting and live bindings, dynamic import, top-level await, and import.meta.

First, the boundaries. The site already has several JavaScript basics guides: array methods, destructuring, Map and Set, Promise and async/await, try/catch, and DOM querying and traversal. This guide covers none of them. It covers one thing: when a single file can no longer hold your code, how to split it into modules and join them back together with import and export. The “Greenstone Cafe” below is the same fictional practice project as before: a small web tool that takes orders for a street-corner cafe. Earlier guides covered how its order page works. This one is about the code itself: the original main.js ran to more than six hundred lines, with the menu, the ordering, the checkout, and the printing all squeezed together, so changing one place meant fearing three others. This guide is about splitting it into canvas.js, menu.js, order.js, and checkout.js, and joining them back together from main.js. Every operation, code sample, and number built around it is invented to explain the technique, not a real record. Everything about module syntax and behavior comes from three MDN pages — “JavaScript modules”, “import”, and “export”. The sources are listed in this article's meta information and evidence record. The examples in the docs — the canvas.js, square.js, and circle.js that draw squares, circles, and triangles, the getPrimes.js that finds primes, and the getColors.js that fetches colors — are the docs' own examples, not real services. This guide does not cover how to configure a bundler, and it does not cover CommonJS require. It covers only native ES modules in the browser. By the end of this guide you should be able to do three things: split code up, join it back together, and rename things when they collide; know that a default export and a named export are not the same thing; and know when dynamic import and top-level await are the right tools.
Step 1: Scripts and modules are two different games — tell them apart first
Before splitting anything, tell two games apart: scripts and modules. MDN says it at the start of “JavaScript modules”: JavaScript code can be evaluated in two ways, as a script — also called a classic script or traditional script — or as a module. There are two main differences. First, at parsing time: modules are automatically in strict mode, and you can only use import and export statements in modules. Second, at runtime: modules are executed in their own scope, not in the global scope. That means variables, functions, and classes declared in a module are not visible outside the module unless they are explicitly exported, or made available globally by attaching them to the global object — window in a browser — which is the poor option. Classic scripts are the opposite: all classic scripts attached to the page are executed under the same scope, the global scope, so a later script can directly use a variable declared by an earlier script. MDN's example is direct: the first script declares a $ function, and the second script calls $.ajax, because both live in the global scope. Convenient, yes, but the cost shows up at scale: scope pollution and identifier conflicts become a big concern. Popular libraries like jQuery and Underscore put everything under special identifiers like $ and _ to minimize the risk, and dependencies have to be managed by the author — if library A uses library B, the author has to add a script element that loads B first, in the right order. Loading on demand is hard too: everything is loaded and initialized as soon as the page loads. Modules exist to clean this up: each module explicitly declares the modules it relies on and the variables it needs from them, so the dependency structure turns from a line into a graph. Remember the rule: scripts all share one global scope; modules each live in their own scope and talk through import and export.
Step 2: Hand things out first — named exports
The first step of splitting is handing things out: for another module to use something from this module, it has to be exported first. MDN's “JavaScript modules” puts it plainly: unlike scripts, where all top-level variables are implicitly accessible to later scripts, you must explicitly export variables for them to be accessible in other modules. The export keyword can go in front of any declaration — var, let, const, function, class, and more — and they need to be top-level items. You cannot use export inside a function, for example. Two forms both work: write it in front of the declaration, export const name = "square" or export function draw(ctx, length, x, y, color) { }, or declare first and hand over a list in curly braces at the end, export { name, draw, reportArea, reportPerimeter }. MDN's example is square.js: a constant name holding the string "square", a draw function that draws a square on a canvas, and reportArea and reportPerimeter functions that write the area and perimeter to a report list — all four exported together. One more rule is worth remembering: export declarations are not subject to temporal dead zone rules. You can write export { x } first and const x = 1 afterwards, and it still works, because export is only a declaration and does not use the value of x. The cafe split it the same way: menu.js exports the menu data with export const MENU and the lookup function with export function findDish(id), and order.js exports the add-to-order function with export function addToOrder(dish). Remember the rule: what is not exported cannot be seen from outside. Exports come in two forms: in front of the declaration, or as a list at the end of the file.
Step 3: Take things in — named imports
Once things are handed out, the second step is taking them in. MDN's “JavaScript modules” writes it as an import statement: the import keyword, a comma-separated list of the names you want inside curly braces, the keyword from, and then the module specifier: import { name, draw, reportArea, reportPerimeter } from "./modules/square.js". Once imported, you use them just like they were defined inside the same file. The module specifier is a string that points to the module. In a browser it is usually a URL relative to the URL of the current module, similar to the href attribute of a link. MDN's example: if main.js is served at https://example.com/basic-modules/main.js and square.js at https://example.com/basic-modules/modules/square.js, then "https://example.com/basic-modules/modules/square.js", "/basic-modules/modules/square.js", and "./modules/square.js" are all equivalent. There is one hard rule in browsers to remember: you cannot omit the file extension or the index.js file name. MDN's “import” page states it clearly: unlike CommonJS, the browser does not try several candidate URLs for one specifier. Writing import x from "./utils" sends a request to exactly that URL, so the extension has to be written in full. To make bare specifiers — plain package names — work in a browser, you need import maps. The cafe's main.js joins things this way: import { MENU, findDish } from "./modules/menu.js" and import { addToOrder } from "./modules/order.js", one line per module, so the dependencies are visible at a glance. Remember the rule: named imports have to match the exported names exactly, the path is a relative URL, and the .js extension cannot be left out.
Step 4: A module can have only one default export
Besides named exports, there is the default export, made for the case where a module is really about one thing. MDN's “JavaScript modules” is clear: default exports have no names associated with them, and each module can have up to one default export. To create one, you export an expression rather than a declaration, by prepending export default to it: export default { some: "object" }, export default 1 + 1, and export default randomSquare all work. Functions and classes are a special case: they are exported as declarations, not expressions, and these declarations can be anonymous, so you can write export default function randomSquare(ctx) { } directly, and the function declaration is hoisted. Importing one takes no curly braces, and you can name it whatever you like — it does not have to match the name on the exporting side: import randomSquare from "./modules/square.js", where randomSquare is a name the importer chose. Named exports and a default export can coexist in the same module. MDN's “export” page also explains a difference that is easy to mix up: export { myFunction as default } exports a live binding, so if myFunction is reassigned later, the importer sees the new value; export default myFunction evaluates myFunction and exports its value at that point, so a later reassignment is not seen by the importer. The cafe's example: checkout.js is mostly one checkout function, so it has export default function checkout(order) { }, and main.js has import checkout from "./modules/checkout.js", named however the importer likes. order.js has both a named export addToOrder and a default export, the Order class, living together. Remember the rule: one default export per module at most, and the importer names it freely. For a live binding use export { x as default }; for the value at that moment use export default x.
Step 5: When names collide — rename with as
With more modules, name collisions are a matter of time. MDN's “JavaScript modules” gives a concrete example: the square, circle, and triangle modules all have functions called draw, reportArea, and reportPerimeter. Importing import { name, draw, reportArea, reportPerimeter } from "./modules/square.js" and then the same four names from "./modules/circle.js" makes the browser throw an error such as "SyntaxError: redeclaration of import name". The fix is the as keyword inside the curly braces of the import or export statement, which changes the identifying name used inside the top-level module: import { name as squareName, draw as drawSquare, reportArea as reportSquareArea, reportPerimeter as reportSquarePerimeter } from "./modules/square.js", with circleName and drawCircle for the circle module and triangleName and drawTriangle for the triangle module, so each module's same-named functions get their own names in main.js. You can also do it on the exporting side instead: export { name as squareName, draw as drawSquare, reportArea as reportSquareArea, reportPerimeter as reportSquarePerimeter }. MDN's advice is to leave the module code alone and make the changes in the imports, especially when you are importing from third-party modules you have no control over. Default exports can use as too: import { default as randomSquare } from "./modules/square.js", because default is a reserved word rather than a valid identifier, so it has to be aliased to be used. The cafe learned this: menu.js and order.js both have a function called format, one formatting the menu and one formatting an order, and importing both directly collides. Renaming to import { format as formatMenu } from "./modules/menu.js" and import { format as formatOrder } from "./modules/order.js" keeps the two apart. Remember the rule: when names collide, rename with as, and prefer doing it on the import side.
Step 6: Take the whole package in — namespace imports
Renaming solves the problem, but it gets wordy when there are many names. A cleaner fix is to take the whole package in: import * as Module from "./modules/module.js", which grabs all the exports available inside the module and makes them available as members of an object called Module, so you write Module.function1() and Module.function2(). MDN's “JavaScript modules” calls this a module namespace object. The example is import * as Canvas from "./modules/canvas.js", import * as Square from "./modules/square.js", import * as Circle from "./modules/circle.js", and import * as Triangle from "./modules/triangle.js", used as Square.draw(myCanvas.ctx, 50, 50, 100, "blue") and Square.reportArea(square.length, reportList). Two details are worth remembering: this namespace object is a sealed object with a null prototype, and the default export sits on it under the key called default — Module.default is the default export. And JavaScript has no wildcard import like import * from "module-name". MDN's “import” page says so explicitly, because of the high possibility of name conflicts. The cafe's main.js ended up written this way: import * as Menu from "./modules/menu.js" and import * as Order from "./modules/order.js", so everything about the menu starts with Menu. and everything about orders starts with Order., and the code reads like a table of contents. Remember the rule: when you use a lot from one module, take the whole package in under a namespace. The default export inside a namespace is called .default.
Step 7: Build one front door — aggregating exports and barrel modules
With more modules, the import statements get longer too. MDN's “JavaScript modules” offers a fix: build one front door. Add a shapes.js that does nothing but gather the exports from circle.js, square.js, and triangle.js together. This is called a barrel module, because it does nothing other than aggregating exports from all other modules. Writing it as import then export takes two steps: import { Circle } from "./shapes/circle.js", import { Square } from "./shapes/square.js", and import { Triangle } from "./shapes/triangle.js", followed by export { Circle, Square, Triangle }. But there is no need to import something just to export it. The export ... from syntax forwards in one line: export { Square } from "./shapes/square.js", export { Triangle } from "./shapes/triangle.js", and export { Circle } from "./shapes/circle.js". There is an even shorter form: export * from "./shapes/square.js", which re-exports all exports other than the default from the target module as named exports of the current module, so if square.js gains a new export later, shapes.js does not have to change. MDN warns about two traps, though. First, export * from does not re-export the default export. Second, if two wildcard export statements implicitly re-export the same name from different bindings, the name is ambiguous and is omitted from the module namespace. Importing it directly throws a syntax error during linking, before evaluation starts, saying the module contains conflicting star exports for that name. MDN's “export” page shows it plainly: mod1.js exports a as 1, mod2.js exports a as 3, barrel.js has two export * from lines, and import * as ns from "./barrel.js" gives ns.a as undefined, while import { a } throws. The cafe's layout: menu.js, order.js, and checkout.js sit in the modules directory, plus an index.js as the front door with export { MENU, findDish } from "./menu.js", export { addToOrder } from "./order.js", and export { default as checkout } from "./checkout.js", so main.js only needs import { MENU, findDish, addToOrder, checkout } from "./modules/index.js" in one line. Remember the rule: build the front door with export ... from. Wildcard forwarding leaves the default export behind, and identical names from different modules turn ambiguous.
Step 8: Run the code without taking anything — side-effect imports and JSON modules
Sometimes a module is imported not to use what is inside it, but to make the code inside it run. MDN's “JavaScript modules” is clear: to run a module's initialization code without importing any of its exports — for example, to install a polyfill — use an import with only a module specifier: import "./modules/polyfills.js". This is called a side-effect import, and it is often used for polyfills, which mutate the global variables. MDN's “import” page says the same: importing an entire module for side effects only runs the module's global code but does not actually import any values. Beyond JavaScript modules, values can also be imported from modules written in other languages, as long as the runtime knows how to interpret them. The specification only defines two other resource types: JSON modules and text modules. A JSON module is basically a standalone JSON file. When imported, it provides a single default export containing the parsed JSON value, written as import data from "./data.json" with { type: "json" }. The trailing with { type: "json" } is an import attribute that tells the runtime to validate that the loaded file is indeed JSON. Text modules work similarly and result in strings: import text from "./text.txt" with { type: "text" }. MDN's advice is that it is good practice to always declare the type of the module you are importing so it can work everywhere. The cafe's example: when the order page starts, it first installs a date patch with import "./modules/polyfills.js" as the first line of main.js, taking no values. The static menu data lives in menu.json, loaded as import menuData from "./data/menu.json" with { type: "json" }, which arrives as a parsed object. Remember the rule: to run code without taking anything, use an import with only the specifier. JSON modules need with { type: "json" }.
Step 9: Imports are hoisted, and bindings are live
import has two temperaments that trip beginners most often: it is hoisted, and the bindings it brings in are live. Hoisting first. MDN's “JavaScript modules” is clear: import declarations are hoisted. The imported values are available in the module's code even before the place that declares them, and the imported module's side effects are produced before the rest of the module's code starts running. MDN's example puts import { Canvas } from "./modules/canvas.js" in the middle of main.js, and the code above it still works with Canvas. But MDN also says it is considered good practice to put all imports at the top of the code, which makes it easier to analyze dependencies. Now live bindings. MDN's “import” page shows it plainly: my-module.js has export let myValue = 1, and half a second later it becomes 2. main.js has import { myValue } from "/modules/my-module.js". Printed at first it is 1; printed a second later it is 2 — the exporting module reassigned it, and the imported value changed. The other direction does not work: the importing module cannot reassign the imported binding. Writing myValue = 3 throws a TypeError, “Assignment to constant variable.” The importing module can only read the value, not reassign it. But one distinction matters: not being able to reassign a binding is not the same as not being able to change an object. When the export is an object, the importing module can mutate the object's properties, and the mutated value can be observed by all other modules importing the same value. MDN's “export” page shows a graph object: main.js replaces graph.options, calls graph.draw(), and cube(3) is still 27 — changes to the object's properties are shared. The cafe's lesson: order.js has export let currentTable = 1. When the cashier side changes it to 5, the order page reads 5, with no message passing needed. But the order page must never write currentTable = 6 — that is a TypeError. Remember the rule: import is hoisted, so write it at the top. Imported bindings are live: read-only for reassignment, but the properties of an imported object can change.
Step 10: Load it when you need it — dynamic import()
Static import has a cost: when the page opens, every module it depends on gets loaded and evaluated. Some modules are rarely needed — the receipt-printing module, for example, is only needed when a customer presses “Print”. MDN's “JavaScript modules” offers dynamic import: the import() operator can be called with the path to the module as a parameter. It returns a Promise, which fulfills with a module namespace object giving you access to that object's exports. It is written as import("./modules/myModule.js").then((module) => { }). MDN's example has three buttons — Circle, Square, and Triangle. Nothing is drawn when the page loads. Pressing a button dynamically loads the required module and then uses it to draw the shape: squareBtn.addEventListener("click", () => { import("./modules/square.js").then((Module) => { const square = new Module.Square(myCanvas.ctx, myCanvas.listId, 50, 50, 100, "blue"); square.draw(); square.reportArea(); square.reportPerimeter(); }); }). Note the Module.Square here: because the promise fulfillment returns a module namespace object, the class becomes a subfeature of the object, so the constructor has to be reached with Module. in front. Dynamic import has another advantage: it is always available, even in script environments. So if you have an existing script tag in your HTML that does not have type="module", you can still reuse code distributed as modules by dynamically importing it. MDN also states its limit: import() will reject if called in a service worker or worklet. The cafe's example: the print module print.js only loads when “Print receipt” is pressed: printBtn.addEventListener("click", () => { import("./modules/print.js").then((m) => m.printReceipt(order)); }). It costs nothing in load time the rest of the day. Remember the rule: do not statically import a module that is rarely used. Load it with import() when it is needed, and what comes back is a namespace object.
Step 11: Top-level await and import.meta — two helpers only modules have
Modules have two more helpers that scripts do not: top-level await and import.meta. Top-level await first. MDN's “JavaScript modules” is clear: the await keyword can be used at the top level, outside any async function. It allows a module to act as a big asynchronous function, meaning it can finish asynchronous work before modules that depend on it execute, without blocking the evaluation of sibling modules that do not depend on it. MDN's example is getColors.js, which fetches the color palette: first a fetch request loads the colors.json file, then export default await colors exports the result. Any other module that includes this one will wait until the colors have been downloaded and parsed before using them. But the independent canvas.js module still evaluates while the colors are being fetched — it is not held up. MDN also warns about the cost: top-level await is not free. It has deep implications, because it means a part of the module graph can only be evaluated asynchronously, so think before using it. Now import.meta. Each module also has its own execution context, accessed through a module-specific import.meta object. The properties of this object are defined by the host environment; the core language spec does not define any properties. In most web-like environments, import.meta.url provides the module's URL, which you can use to locate a resource relative to the module: const colorsURL = new URL("../data/colors.json", import.meta.url). This keeps the resource URL relative to getColors.js even when the module is imported from a page or module in another directory — moving the module does not break the address. The cafe's example: getMenu.js uses top-level await to fetch the menu data first and then export it, so main.js receives it ready to use. The print template address is computed with new URL("./templates/receipt.html", import.meta.url), so moving the module to another directory needs no address change. Remember the rule: top-level await only works inside modules, and modules that depend on it will wait. import.meta.url is the module's own address — use it to compute relative resource addresses.
Step 12: Counting the mistakes — six kinds of error made up all of them
The chart below is a fictional tally: 132 splitting and referencing mistakes in one month while the Greenstone Cafe order page was being split out of main.js into modules, split into six causes. The numbers are invented to make the point, not a real record. The largest group forgot the .js extension or wrote the path wrong: 32 mistakes, 24.2%, matching Step 3. Second, named exports whose names did not match: 28 mistakes, 21.2%, matching Steps 3 and 5. Third, a default export imported as if it were named, with the braces the wrong way round: 24 mistakes, 18.2%, matching Step 4. Fourth, same-name import collisions left unrenamed: 20 mistakes, 15.2%, matching Step 5. Fifth, reassigning an imported value on the importing side: 16 mistakes, 12.1%, matching Step 9. Sixth, opening the page directly with file:// and getting a cross-origin error from the module: 12 mistakes, 9.1%, matching the two traps below. The six groups add up to 32 + 28 + 24 + 20 + 16 + 12 = 132, and the percentages add up to 24.2 + 21.2 + 18.2 + 15.2 + 12.1 + 9.1 = 100.0. The books balance. Read the chart for the pattern, not the ranking: the top three mistakes are all “the writing did not line up” — the extension, the names, the braces. The last three are all “the rule was not remembered” — live bindings cannot be reassigned, and file:// cannot run modules. Fix the writing first, then remember the rules.
Step 13: Two traps and a checklist to run through after writing module code
Finally, two traps, both written in black and white in MDN's “export” page and “JavaScript modules” guide. The first trap: you cannot run JavaScript modules through a file:// URL. You will get CORS errors. You need to run them through an HTTP server. Start a static server locally and open the page through it, and the problem disappears. The second trap: the server has to serve module files with a JavaScript MIME type. MDN's “JavaScript modules” is clear: to get modules to work correctly in a browser, you need to make sure your server is serving them with a Content-Type header that contains a JavaScript MIME type such as text/javascript. If you do not, you will get a strict MIME type checking error, and the browser will not run your JavaScript. Most servers set the correct type for .js files automatically, but some do not for .mjs files — one reason MDN suggests using .js during development and converting to .mjs during the build step. The checklist has nine items. First, did I export what the module declares — what is not exported cannot be seen from outside. Second, do the named import names match the exporting side. Third, is the .js extension written in full in the path, and is the relative address right. Fourth, is there only one default export per module, and are the braces right on import. Fifth, are same-name imports renamed, preferably on the import side. Sixth, when one module is used a lot, did I take the whole package in under a namespace. Seventh, in the front door's forwarding, does the default export need to be forwarded separately, and could wildcard forwarding collide on a name. Eighth, is the imported binding only read and never reassigned — and am I changing the object's properties instead. Ninth, are rarely used modules switched to dynamic import, and is the page opened through an HTTP server. When all nine pass, the module code is done. When one fails, go back and fix it — do not count on the browser's error message to guess it for you.
Comments (0)
Sources
Related articles
Flexbox lays things out in one direction at a time, and when it is done right, the nav bar, the card wall, and the cart rows all behave. This guide follows MDN's Basic concepts of flexbox, Aligning items in a flex container, and Controlling ratios of flex items along the main axis: the two axes, containers and items, direction and wrapping, free space, the three flex properties, alignment on both axes, and gaps and auto margins.
One order is one object: table, dishes, total, paid — all filed by label. This guide follows MDN's Working with objects, JSON, and Object references: object literals, dot vs bracket notation, adding and deleting properties, for...in with hasOwn, methods and this, getters and setters, references vs copies, Object.assign and friends, null-prototype objects, JSON's strict rules, and stringify and parse with their number-precision trap.
You already call functions every day; this guide names what you have been doing. Following MDN's Functions, Arrow function expressions, and Rest parameters: declarations versus expressions, parameters and arguments, default values, rest parameters, spread syntax, return values, arrow function shorthand, the this trap, callbacks, and scope.