Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 38 ยท Entry, Output and Loaders

Resolve, Extensions and Aliases

Understand how Webpack finds modules: resolve.extensions, alias, modules, mainFields, conditionNames, package exports, symlinks and fixes for the common Module not found error.

When you write import { fmt } from './format' or import React from 'react', Webpack must turn that string into a file on disk. That step is called resolving, and the resolve section of the config controls it. Most "Module not found" errors are resolving problems, so it pays to know the rules.

How a request is resolved

There are two kinds of requests:

  • Relative or absolute (./format, ../lib/util, /abs/path): looked up directly from the importing file.
  • Module requests (react, lodash/debounce, @scope/pkg): searched in node_modules folders, walking up from the importing file, using the package's package.json.

For a path that points to a file, Webpack tries the exact name, then adds each entry of resolve.extensions. For a path that points to a folder, it looks for a package.json field or an index file.

flowchart TB
  R["import './format'"] --> A{"file 'format' exists?"}
  A -->|no| B["try format.js, format.json, ..."]
  B -->|no| C{"folder 'format/'?"}
  C -->|yes| D["package.json main or index.js"]
  C -->|no| E["Module not found"]

Webpack tries the exact file, then extensions, then a folder entry.

Node.js Stand-in: a tiny resolver

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

resolve.extensions

By default Webpack resolves .js, .json and .wasm. Anything else (TypeScript, JSX) must be listed, in the order you want them tried:

JavaScript
resolve: {
  extensions: ['.tsx', '.ts', '.jsx', '.js', '.json'],
},

Each extra extension makes failed lookups slower, so list only what you use. Importing with the extension (./format.ts) always works and skips the search. (For TypeScript, .ts in import paths needs a compatible tsconfig option; check your setup.)

resolve.alias

An alias replaces a path prefix with another path. It is the cure for imports like ../../../../components/Button.

JavaScript
const path = require('node:path');

resolve: {
  alias: {
    '@': path.resolve(__dirname, 'src'),
    '@components': path.resolve(__dirname, 'src/components'),
    react$: path.resolve(__dirname, 'vendor/react-patched.js'),
  },
},

Now import Button from '@components/Button' works from any depth. A trailing $ makes the alias match the exact request only, so react$ changes react but not react/jsx-runtime. Aliases also swap implementations: point lodash to lodash-es for better tree shaking, or mock a module in a test build.

Editors and TypeScript do not read Webpack's config. Add the same mapping to tsconfig.json (compilerOptions.paths with baseUrl) so autocompletion and type checking understand your aliases.

resolve.modules

resolve.modules lists folders searched for module requests. The default is ['node_modules'], which means "walk up the tree". Add a folder to import from it directly:

JavaScript
resolve: {
  modules: [path.resolve(__dirname, 'src'), 'node_modules'],
},

With this, import util from 'utils/date' finds src/utils/date.js. Aliases are usually clearer because the special prefix tells readers it is not an npm package.

Packages: mainFields and exports

A package tells bundlers which file to load, in two ways:

  • Old style: main, module and browser fields. resolve.mainFields sets the order Webpack tries them. For a web target it is ['browser', 'module', 'main'].
  • Modern style: the exports field with conditions such as import, require, browser, development, production. resolve.conditionNames controls which conditions match.
JSON
{
  "name": "tiny-lib",
  "exports": {
    ".": {
      "import": "./esm/index.js",
      "require": "./cjs/index.js"
    },
    "./utils": "./esm/utils.js"
  }
}

If a package has exports, only the listed paths can be imported: tiny-lib/internal/secret.js fails even though the file exists. That is by design, so authors can hide internals.

Node.js Stand-in: choosing a package entry by conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Other useful options

  • resolve.fallback: Webpack 5 no longer polyfills Node core modules in the browser. If a dependency needs path or crypto, add a fallback package ({ path: require.resolve('path-browserify') }) or set it to false to ignore the module.
  • resolve.symlinks: whether symlinked packages (monorepos, npm link) are resolved to their real path. The default true is usually right.
  • resolve.plugins: for example tsconfig-paths-webpack-plugin reads aliases from tsconfig.json so you define them once.
  • resolveLoader: the same settings but for finding loaders.

Fixing "Module not found"

  1. Read the error: it prints the request and the folder it started from.
  2. Check spelling and case. macOS and Windows ignore case, Linux CI does not.
  3. Missing extension? Add it to resolve.extensions or write it in the import.
  4. A package that is not installed, or only a dev dependency in a production install.
  5. A Node core module in browser code: add resolve.fallback.
  6. The package exports map hides the path you want.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does resolve.extensions: ['.ts', '.js'] let you do?

    Extensions are tried in order when an import path has none; compiling TS still needs a loader.
  2. 2. What does the $ in alias { react$: '...' } mean?

    A trailing $ makes the match exact.
  3. 3. Why does tsconfig need paths when you use Webpack aliases?

    Only Webpack knows the alias; the TypeScript compiler needs its own mapping to type check imports.
  4. 4. A package defines an exports map without './internal.js'. What happens when you import 'pkg/internal.js'?

    With exports, only declared subpaths are importable.

Summary

  • Resolving turns import strings into files: relative lookup, then node_modules walking.
  • resolve.extensions lists the extensions to try; alias rewrites path prefixes ($ for exact match).
  • resolve.modules, mainFields and conditionNames control folders and package entry selection.
  • exports maps both choose conditional files and hide internals.
  • Mirror aliases in tsconfig.json, and use fallback for Node core modules in browser code.

Next: HTML Webpack Plugin