Skip to content
Visual explainer 3h to learn 4 steps

ES modules, npm & tooling

Set up a project with npm, ES modules and a dev server.

By Invicly Tech, , in Frontend with React & Next.js. About 8 minutes to read.

Topic 9 of 36

In short

ES modules split code into files that import and export values. npm installs third-party packages, and a dev server like Vite serves your modules with instant reloads.

Explained simply

As a project grows, one huge JavaScript file becomes impossible to manage. ES modules let you split code into many files. Each file chooses what to share with export, and other files ask for those things with import.

Each module has its own private scope. A variable inside math.js is invisible to other files unless it is exported. This stops files from accidentally overwriting each other's names, a common bug in older websites.

npm is a package manager and an online registry of free code packages. Instead of writing a date library yourself, you run npm install and import it. package.json lists what your project needs, so anyone can install the same things.

Tooling ties it together. A dev server like Vite serves your modules, reloads the page instantly when you save, and later bundles everything into small, fast files for production. You write clean modules; the tools handle the delivery.

Press Play on a diagram to walk through it one step at a time.

FlowFrom empty folder to running app
  1. 1
    npm init

    Creates package.json to track scripts and dependencies

  2. 2
    npm install

    Adds packages to node_modules and the lockfile

  3. 3
    import / export

    Split code into modules that share values

  4. 4
    npm run dev

    Vite serves modules with hot reload

  5. 5
    npm run build

    Bundles and minifies files for production

MapA small project's import graph
main.js (entry)
  • ./ui/cart.js
    • ./utils/format.js
    • ./api/client.js
  • ./ui/header.js
    • ./utils/format.js
  • dayjs (from npm)
  • ./styles.css (handled by Vite)
CompareDev server vs production build
npm run dev
  • Serves source files as modules
  • Instant reload on save
  • No minification
  • Readable errors and source maps
npm run build
  • Bundles and tree-shakes code
  • Minifies and adds content hashes
  • Splits chunks at dynamic imports
  • Output in dist/ for any static host

In depth

Named vs default exports

A named export shares a value under its own name: export function add() {}. Importers must use that name in braces, import { add } from "./math.js", optionally renaming with as. A file can have many named exports.

A default export is the file's main thing: export default function Button() {}. Importers pick any name without braces. A file can have only one.

Many teams prefer named exports because editors can auto-import them, renames are tracked across the project, and typos fail loudly. Frameworks sometimes require defaults, such as Next.js page files.

CompareNamed vs default export
Named
  • export function add() {}
  • import { add } from "./math.js"
  • Many per file
  • Name must match (or use as)
Default
  • export default function Button() {}
  • import AnyName from "./Button.js"
  • One per file
  • Importer picks the name

How module loading works

Imports are static: they sit at the top of a file and cannot be inside an if. This lets tools read the whole import graph before running anything. Each module runs only once, no matter how many files import it, and everyone shares the same instance.

Imports are live bindings, not copies: if the exporting module changes an exported let, importers see the new value. When you need to load code later, for example a heavy chart library only when a user opens a tab, use dynamic import("./chart.js"), which returns a promise. Bundlers split dynamic imports into separate files automatically.

  • Static import: known at build time
  • Each module runs once and is cached
  • Dynamic import(): load on demand
  • Top-level await works in modules

Versions, ranges and lockfiles

Packages use semantic versioning: MAJOR.MINOR.PATCH. A patch fixes bugs, a minor adds features without breaking anything, and a major may break your code.

In package.json, "^1.4.2" allows any 1.x.x from 1.4.2 up, and "~1.4.2" allows only 1.4.x. The lockfile records the exact version actually installed, including every sub-dependency. Commit it. On CI, use npm ci, which installs exactly what the lockfile says and fails if it does not match package.json.

CompareWhat each version range allows
^1.4.2
  • 1.4.2 up to, not including, 2.0.0
  • New minors and patches
  • npm install default
~1.4.2
  • 1.4.2 up to, not including, 1.5.0
  • Patches only
  • Fewer surprise updates
1.4.2
  • Exactly 1.4.2
  • No range at all
  • Updated only by hand

dependencies vs devDependencies

dependencies are needed when your app runs, like react. devDependencies are only needed to build and test, like vite, typescript or vitest; install them with npm install -D. For a website the bundle only includes what you actually import, but keeping the split clear makes server installs smaller and intent obvious. Scripts in package.json, such as "dev": "vite", let everyone run the same commands with npm run dev.

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Initialise a project with npm~45m
  2. 2
    Use import and export modules~45m
  3. 3
    Install and use packages~45m
  4. 4
    Run a Vite dev server~45m

Key points

  • package.json lists dependencies and scripts; the lockfile pins exact versions.
  • Commit the lockfile but never commit node_modules.
  • A module can have many named exports and at most one default export.
  • Dev servers serve modules fast; build tools bundle them for production.

Key terms

Tap a card to flip it. 0/5 known

Examples

js
// math.js
export function add(a, b) {
  return a + b;
}
export default function square(n) {
  return n * n;
}

// main.js
import square, { add } from './math.js';
console.log(add(2, 3), square(4));

// Terminal: npm create vite@latest my-app

Named and default exports, imported in another file.

Starting a Vite project from scratch

Step 1: run npm create vite@latest my-app and pick Vanilla. Step 2: cd my-app and run npm install, which reads package.json and creates node_modules and package-lock.json. Step 3: npm run dev starts the server at a local URL. Step 4: add a package with npm install dayjs and import it in main.js. Step 5: npm run build writes optimised files to dist/.

bash
npm create vite@latest my-app -- --template vanilla
cd my-app
npm install
npm install dayjs
npm run dev      # local dev server with hot reload
npm run build    # production files in dist/

Splitting a price formatter into a module

Two pages both format prices. Step 1: create format.js with a named export. Step 2: import it in both files. Step 3: the formatter now lives in one place, so a fix applies everywhere. Note the ./ and the .js extension: browsers need a real path for local files.

js
// format.js
export function formatPrice(cents, currency = "USD") {
  return new Intl.NumberFormat("en-US", { style: "currency", currency })
    .format(cents / 100);
}

// cart.js
import { formatPrice } from "./format.js";
console.log(formatPrice(1999)); // $19.99

Quick reference

  • export function f() {} / import { f } from "./f.js"
  • export default X / import AnyName from "./x.js"
  • Rename on import: import { add as sum } from "./math.js"
  • Lazy load: const mod = await import("./heavy.js")
  • npm install pkg (dependency); npm install -D pkg (dev only)
  • Use npm ci in CI for exact, lockfile-based installs
  • Commit package-lock.json; ignore node_modules
  • ^1.2.3 allows 1.x updates; ~1.2.3 allows 1.2.x only

Common mistakes

  • Mixing require and import in the same project without understanding the difference.
  • Installing build-only tools as regular dependencies instead of devDependencies.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A module is imported by 5 different files. How many times does its top-level code run?

Question 2

2Which version range allows 2.4.0 if package.json says "^2.1.0"?

Question 3

3What is dynamic import() mainly used for?

Question 4

4Where should vitest be listed?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Create math.js with named exports add and multiply, and a default export average. Import all three in main.js.

  2. Exercise 2medium

    Add a script to package.json so npm run check runs both lint and tests (assume eslint and vitest are installed).

  3. Exercise 3hard

    A page imports a 400 KB charting library at the top, but the chart only shows after clicking "Show stats". Change it to load the library only on click.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between npm and npx?
npm installs and manages packages. npx runs a package's command, downloading it temporarily if needed, such as npx eslint.
Why do imports need the .js extension in the browser?
Browsers load modules by URL and do not guess file names. Bundlers like Vite and Node with TypeScript settings can resolve extensionless imports for you.
What are CommonJS and require?
CommonJS is Node's older module system using require and module.exports. New code should use ES modules, which work in both browsers and modern Node.

Go deeper

ShareXLinkedInWhatsApp