Webpack interview questions: config, code splitting and build performance
Webpack interview questions check whether you understand what a bundler does with your code: how webpack builds a dependency graph from an entry point, how loaders transform files and plugins hook into the build, and how output hashing, code splitting and tree shaking affect what users download. Fundamentals questions cover the core config, intermediate ones cover caching, source maps and performance, and senior ones ask you to speed up a slow build, shrink a bundle, design micro-frontends or weigh webpack against Vite. Explain the mechanism, then the config line that controls it.
By Evin JohnPublished 10 min read
How webpack comes up in front-end interviews
Few interviews are about webpack alone. It usually appears inside a front-end, full-stack or platform round as "how does your build work?", "our bundle is too big, what do you do?" or "why is the dev server slow?". Teams with a large, older React or Angular codebase ask more, since someone has to own the config. Teams that moved to Vite or a framework's built-in tooling still ask the concepts, because code splitting, hashing and tree shaking work the same way underneath. Expect to read a config file, predict what a change does, and explain the trade-off in plain words.
Fundamentals
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What does webpack do? | Purpose | It starts at one or more entry files, follows every import and require to build a dependency graph, transforms each module with loaders and writes one or more bundles (chunks) the browser can load. |
| Name the core configuration concepts. | Vocabulary | Entry (where the graph starts), output (where and how bundles are written), loaders (per-file transforms), plugins (whole-build features), mode (development or production defaults), plus resolve rules for finding modules. |
| Loader versus plugin? | Core distinction | A loader takes one file's source and returns transformed source, such as TypeScript to JavaScript. A plugin taps into the compiler's lifecycle hooks and can touch the whole compilation, such as generating HTML or extracting CSS into files. |
| In what order do loaders run? | Detail | Within one rule's use array, from last to first (right to left). In ["style-loader", "css-loader"], css-loader resolves imports in the CSS first, then style-loader injects the result into the page. |
What does mode change? | Defaults | Production turns on minification, tree-shaking flags, scope hoisting and production values for process.env.NODE_ENV. Development favors fast rebuilds and readable output. |
| What is a chunk, and how is it different from a bundle or module? | Terms | A module is one source file in the graph. A chunk is a group of modules webpack decides to emit together. A bundle is the emitted file for a chunk. |
| How does webpack handle images and fonts in webpack 5? | Asset modules | Built-in asset module types replace the older file-loader and url-loader: asset/resource emits a file, asset/inline embeds a data URL, and asset chooses by size. |
What do resolve.extensions and resolve.alias do? | Resolution | Extensions let imports omit file endings; aliases map a short prefix such as @ to a folder. Mirror aliases in the TypeScript and test runner config, or editors and tests break. |
| Why does webpack 5 complain about missing Node core modules in browser code? | Migration | Webpack 4 added browser polyfills for modules like crypto or buffer automatically; webpack 5 stopped doing that. You add a polyfill through resolve.fallback or remove the dependency on it. |
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = (env, argv) => {
const isProd = argv.mode === "production";
return {
entry: { main: "./src/index.js" },
output: {
path: path.resolve(__dirname, "dist"),
filename: isProd ? "[name].[contenthash].js" : "[name].js",
clean: true, // empty dist before each build
},
devtool: isProd ? "source-map" : "eval-cheap-module-source-map",
module: {
rules: [
{ test: /\.jsx?$/, exclude: /node_modules/, use: "babel-loader" },
// loaders run right to left: css-loader first, then style-loader
{ test: /\.css$/, use: ["style-loader", "css-loader"] },
{ test: /\.(png|svg|jpg)$/, type: "asset/resource" },
],
},
resolve: { extensions: [".js", ".jsx"], alias: { "@": path.resolve(__dirname, "src") } },
plugins: [new HtmlWebpackPlugin({ template: "./src/index.html" })],
optimization: {
splitChunks: { chunks: "all" }, // vendor code into its own cacheable chunk
runtimeChunk: "single",
moduleIds: "deterministic", // stable ids keep hashes stable
},
devServer: { hot: true, historyApiFallback: true },
};
};Intermediate: caching, source maps and the dev loop
- What is the difference between fullhash, chunkhash and contenthash? Fullhash (called hash in older versions) changes when anything in the build changes. Chunkhash changes when a chunk's modules change. Contenthash depends only on the emitted file's content, so it is the usual choice for long-term browser caching.
- Why do vendor hashes sometimes change when you only edited app code? The webpack runtime and module ids can leak into every chunk. Extracting the runtime into its own chunk (
runtimeChunk: "single") and using deterministic module ids keeps unrelated hashes stable. - Which source map setting would you use in development and in production? A fast option such as
eval-cheap-module-source-mapwhile developing. In production, fullsource-maporhidden-source-mapuploaded privately to an error tracker, depending on whether you want maps public. - How does hot module replacement work? The dev server keeps a socket open to the page. When a file changes, webpack rebuilds the affected modules and sends an update; the runtime swaps them in place, and framework integrations such as React Fast Refresh keep component state. If a module cannot accept the update, the page reloads.
- What does `historyApiFallback` fix? Client-side routes like
/settingsreturn 404 from a plain dev server on refresh. The fallback serves index.html for unknown paths so the router can handle them. - How do you inject environment values into the bundle? DefinePlugin replaces expressions such as
process.env.API_URLwith literal values at build time. Anything injected this way is visible to anyone who opens the bundle, so never put secrets there. - What is `publicPath` and when does it break things? The URL prefix webpack uses to load chunks and assets at run time. A wrong value shows up as lazy chunks or images loading from the wrong path, typically after moving assets to a CDN or a subfolder.
- How does webpack handle CSS in production? Commonly with mini-css-extract-plugin, which writes real CSS files that browsers can cache and load in parallel, instead of style-loader injecting styles from JavaScript.
Intermediate: code splitting and tree shaking
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What are the ways to split code in webpack? | Splitting | Multiple entry points, dynamic import() for lazy loading, and optimization.splitChunks to pull shared and vendor modules into separate chunks. |
| How does dynamic import create a chunk? | Lazy loading | Webpack sees import() with a static path, puts that module and its unique dependencies in a new chunk, and emits runtime code that fetches it with a script request when the call runs. |
| What are prefetch and preload hints? | Loading strategy | Magic comments webpackPrefetch and webpackPreload add resource hints. Prefetch fetches likely future chunks when the browser is idle; preload fetches something needed for the current navigation in parallel. |
| What is tree shaking, and what does it require? | Dead code | Removing exports nobody imports. It needs ES module syntax that can be analyzed statically, production mode so unused exports are marked and minified away, and packages that do not hide side effects. |
What does sideEffects in package.json do? | Library hints | "sideEffects": false tells webpack that importing a module only matters for its exports, so unused modules can be dropped entirely. List files that must stay, such as CSS imports, as an array. |
| Why might a library not tree-shake? | Debugging | It ships CommonJS, re-exports everything through one barrel file with side effects, or is imported as a whole (import _ from "lodash"). Use the ES module build or per-function imports. |
| How do you find out what is in your bundle? | Tooling | Generate stats with webpack --json or use webpack-bundle-analyzer, then look for duplicated packages, oversized dependencies and code that should be lazy. |
| What is scope hoisting? | Output | In production, webpack concatenates ES modules into one scope where possible, which removes per-module wrapper functions and makes output smaller and faster to run. |
async function openChart(el, data) {
const { renderChart } = await import(/* webpackChunkName: "chart" */ "./chart.js");
renderChart(el, data);
}Senior and scenario questions
- A production build takes many minutes. How do you speed it up? Measure first (per-loader timing, a speed profile). Then turn on the webpack 5 persistent cache (
cache: { type: "filesystem" }), limit loaders withincludeandexclude, replace Babel or ts-loader with a faster transpiler such as esbuild-loader or swc-loader while keeping type checks in a separate process, and drop source maps or plugins you do not need. - The main bundle grew sharply after a release. What do you do? Compare bundle stats between the two builds, find the new or duplicated dependency, check whether it was imported whole, and move rarely used features behind dynamic imports. Add a size budget to CI so it cannot happen silently again.
- How would you build micro-frontends with webpack? Module Federation, added in webpack 5, lets one build load modules exposed by another at run time. Declare shared dependencies such as React as singletons, version the remote entry files, and plan for a remote being unavailable.
- Webpack or Vite for a new project? Vite serves native ES modules in development, so startup and updates stay fast as the app grows, and it uses Rollup-style bundling for production. Webpack has the largest plugin ecosystem and fine control for unusual builds. For a typical new app, many teams choose Vite or the framework's own tooling; for a big existing webpack app, migration needs a reason.
- How would you migrate a large app from webpack to Vite? Inventory custom loaders, plugins, aliases and environment variable usage, find Vite equivalents, migrate one app or package at a time, compare bundle size and behavior, and keep both builds working until parity is proven.
- How do you build a library with webpack rather than an app? Set
output.librarywith a type such as module or umd, mark peer dependencies like React asexternalsso they are not bundled, and emit ES modules so consumers can tree-shake. Many teams use Rollup or a library-focused tool instead. - Two copies of React end up in the bundle and hooks break. Why? Different versions or paths resolve to separate copies, often through linked packages or a micro-frontend. Fix with dependency deduplication, a resolve alias to one copy, or a singleton shared module in Module Federation.
- Explain what the webpack runtime does. It is the small piece of code that keeps a registry of modules, implements the require function inside the bundle, and loads lazy chunks on demand. It is why the runtime chunk changes when the chunk map changes.
- Write a minimal loader and a minimal plugin. A loader is a function from source to source. A plugin is a class with
apply(compiler)that taps hooks such asdoneorthisCompilation. The snippet below shows both and tests them without webpack.
// A loader is a function from source text to source text.
function stripDebugLoader(source) {
return source.split("\n").filter((line) => !line.trim().startsWith("console.debug(")).join("\n");
}
// A plugin is an object with apply(compiler) that taps compiler hooks.
class SizeReportPlugin {
constructor(limitKb) { this.limitKb = limitKb; }
apply(compiler) {
compiler.hooks.done.tap("SizeReportPlugin", (stats) => {
const { assets } = stats.toJson({ assets: true });
for (const a of assets) {
const kb = (a.size / 1024).toFixed(1);
const flag = a.size / 1024 > this.limitKb ? " <-- over budget" : "";
console.log(a.name + " " + kb + " KiB" + flag);
}
});
}
}
// Both can be exercised without webpack, using a fake compiler:
console.log(stripDebugLoader("const a = 1;\nconsole.debug(a);\nexport default a;"));
const taps = [];
const fakeCompiler = { hooks: { done: { tap: (name, fn) => taps.push(fn) } } };
new SizeReportPlugin(200).apply(fakeCompiler);
taps[0]({ toJson: () => ({ assets: [{ name: "main.js", size: 51200 }, { name: "vendors.js", size: 307200 }] }) });
// const a = 1;
// export default a;
// main.js 50.0 KiB
// vendors.js 300.0 KiB <-- over budgetconst { ModuleFederationPlugin } = require("webpack").container;
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: "shell",
remotes: { checkout: "checkout@https://cdn.example.com/checkout/remoteEntry.js" },
shared: { react: { singleton: true }, "react-dom": { singleton: true } },
}),
],
};Fictional example
- Interviewer
- Users on mid-range phones wait a long time before the dashboard responds. You own the build. What do you look at?
- Candidate
- First I would confirm with a performance trace that JavaScript is the bottleneck rather than the API. If it is, I would run the bundle analyzer on the production build. In apps like this I usually find three things: one large entry chunk because every route is imported eagerly, a heavy dependency such as a charting or date library pulled in whole, and duplicated packages at different versions. I would lazy-load each route with dynamic import, so the dashboard ships only its own code, switch the heavy library to per-function imports or a lighter alternative, and deduplicate versions. I would check that tree shaking works by confirming the packages ship ES modules and declare side effects honestly. Then I would add contenthash file names with a separate runtime chunk so returning users hit the cache, and set a bundle size budget in CI. I would report before and after numbers from the same device profile, not just bundle sizes.
A two-week webpack practice plan
- Days 1 to 3: build a config from an empty folderNo starter kit. Add entry and output, a JavaScript and a CSS rule, an HTML plugin and the dev server, and explain each line to yourself.
- Days 4 and 5: production outputSwitch to production mode, add contenthash, a runtime chunk and splitChunks, and watch which file names change when you edit one module.
- Days 6 and 7: split and shakeLazy-load a route with dynamic import, import a large library two ways, and compare the analyzer output.
- Days 8 and 9: write a loader and a pluginKeep them tiny, as in the snippet above, so you can talk through the compiler hooks with confidence.
- Days 10 to 12: speedMeasure a cold and a warm build, enable the filesystem cache, and try a faster transpiler. Note the numbers on your own machine.
- Days 13 and 14: the comparison questionsWrite short answers to webpack versus Vite, Rollup and esbuild, and to when Module Federation is worth its complexity.
Bundler questions sit beside the language and framework ones: see JavaScript interview questions, React interview questions and the front-end developer guide. Webpack's own architecture (a plugin system built on hooks, loaders chained in order) is a nice real-world example for design patterns interview questions.
Build questions are often asked by showing you a config on screen and asking what it does. For practice, Natively, an AI interview assistant on Mac and Windows, can read a config or error output from a screenshot and explain it, give coding help in a mock round, and keep a transcript of your answers so you can hear whether you explained the mechanism or only named the setting. Add your résumé and the job description (Pro or the free trial) and its suggestions match the stack you list.
Questions people ask
What are the most common webpack interview questions?
Loader versus plugin, entry and output, what mode changes, contenthash and caching, source map choices, hot module replacement, code splitting with dynamic import, tree shaking and sideEffects, speeding up builds, and webpack versus Vite.
What is the difference between a loader and a plugin in webpack?
A loader transforms one file's source as it is imported, for example TypeScript or CSS. A plugin hooks into the compiler's lifecycle and can act on the whole build, for example generating HTML or extracting CSS files.
How does tree shaking work in webpack?
In production mode webpack marks exports that nothing imports and the minifier removes them. It only works on ES modules, and packages should declare sideEffects so whole unused modules can be dropped.
Should I still learn webpack if teams are moving to Vite?
Yes, if the jobs you target maintain existing webpack apps, and in any case the concepts carry over: dependency graphs, code splitting, hashing and tree shaking work the same way in other bundlers.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
