Skip to content

Lesson 4 of 9 · 22m

Module Resolution in the Real World

Relative paths, bare specifiers, package exports, conditions, aliases, and why TypeScript and bundlers can resolve the same import differently.

Module resolution is where theoretical JavaScript meets fifteen years of packaging history. The resolver is not just looking for files; it is interpreting contracts. import "./x" asks the filesystem. import "react" asks package metadata. import "@/x" asks your build tool to honor a private convention. Treat those as different namespaces and half the mystery disappears.

Relative and bare imports are different species

import localThing from "./localThing";       // relative filesystem lookup
import react from "react";                  // package lookup in node_modules
import Button from "@/components/Button";   // alias convention, not a standard

A relative import is predictable: extensions may be inferred by tooling, but the target is anchored to the importer. A bare import searches package graphs and can be affected by hoisting, nested node_modules, peer dependencies, and package manager linking.

exports is a locked door, not a suggestion

Modern packages define their public surface explicitly:

{
  "name": "acme-ui",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/index.mjs",
      "require": "./dist/index.cjs"
    },
    "./button": "./dist/button.mjs"
  }
}

If acme-ui/dist/internal.mjs exists but is not exported, importing it is invalid even though the file is present. Webpack historically papered over this in some configurations; Vite and modern Node are stricter. Deep-import hacks become migration bugs.

Aliases must be aligned everywhere

// vite.config.ts
resolve: {
  alias: { "@": fileURLToPath(new URL("./src", import.meta.url)) }
}

That teaches Vite. TypeScript also needs:

{ "compilerOptions": { "baseUrl": ".", "paths": { "@/*": ["src/*"] } } }

Tests, Storybook, SSR loaders, and sometimes ESLint need the same mapping. If only one resolver understands @/, every import is a future inconsistency report.

Conditional exports choose the environment

Packages can expose different files for browser, node, development, and production. This is useful and dangerous: a library may genuinely load different implementations in SSR and browser builds. When debugging, log or inspect what was resolved rather than assuming package root behavior.

Field notes

  • Case sensitivity matters: macOS often forgives Button.tsx vs button.tsx; Linux CI does not.
  • Missing extensions are a bundler convenience. Node ESM usually requires the full filename.
  • Circular dependencies can resolve successfully yet evaluate partially initialized bindings.
  • Use vite --debug or resolver plugins when needed, but first verify node_modules actually contains what lockfiles claim.

Was this lesson helpful?

Sign in to rate