webpack Documentation

repository·main·Indexed 11 days ago

https://github.com/webpack/webpack.js.org

Official documentation, guides, and conceptual explanations for the webpack module bundler. Includes instructions on configuration, using webpack-cli, managing Module Federation, and migrating from webpack 4 to webpack 5.

Tokens
229.3K
Snippets
816
Records
1.1K
Agent score
79%

What's inside webpack

  1. Explore Webpack Integration Libraries and Tools

    main

    Beyond loaders and plugins, the ecosystem includes libraries to integrate Webpack into different workflows and tools to manage it:

    • Integration Libraries: Tools like dotenv-webpack for environment variables, webpack-stream for Gulp, and Webpacker for Ruby on Rails.
    • Development Tools: Webpack Dev Server for serving apps with hot reloading, Webpack Dev Middleware for live bundles, and Webpack Dashboard for a CLI dashboard.
    • Configuration & Management: Webpack Merge for combining configurations, Webpack Validator for config validation, and Neutrino for preset-based configuration.
    • Analysis Tools: Webpack Bundle Analyzer and BundleStats for monitoring bundle size and assets across builds.
  2. Understand the licenses for webpack and its documentation

    main

    The webpack ecosystem uses different licenses for its core software, media assets, documentation content, and code samples:

  3. Explore Webpack Loaders

    main

    Webpack loaders allow you to transform files in your project (e.g., converting TypeScript to JavaScript, or SASS to CSS) before they are added to the bundle. The ecosystem provides various categories of loaders:

    • File Type: Handle HTML, images (responsive, SVG, Imagemin), diagrams (mermaid), WebAssembly (wasm), and GraphQL.
    • Component & Template: Support for frameworks like Angular (Template, ngTemplate, ngInlineStyles), Vue, React (SVG to React), Handlebars, Pug, Nunjucks, and Riot.
    • Styles: Transform CSS, SASS, Less, Stylus, and PostCSS, or handle CSS-in-JS.
    • Language & Framework: Support for TypeScript (ts-loader), CoffeeScript, Elm, Lua (Fengari), and MDX.
    • Utility: Essential tools like Babel loader, Worker loader, esbuild loader, and various icon/font loaders.
    • Testing: Integration with Karma and Istanbul for code coverage.
  4. Understand webpack core terminology

    main

    This glossary provides definitions for key concepts used throughout the webpack ecosystem to help you navigate configuration, bundling, and module management.

    Core Concepts

    • Module: Discrete chunks of functionality that provide a smaller surface area than a full program.
    • Dependency Graph: A recursive map built by webpack starting from entry points that includes every module and asset required by the application.
    • Entry Point: The contextual root(s) where webpack starts building the dependency graph.
    • Chunk: An internal webpack abstraction used to manage the bundling process. Bundles are composed of chunks (e.g., entry and child chunks).
    • Bundle: The final version of source files produced after the loading and compilation process.
    • Asset: General term for files like images, fonts, and media used in applications. These can be output as individual files or inlined via loaders.
    • Output: Configuration options that specify where compiled files are written to disk. Note that while you can have multiple entry points, you can only specify one output configuration.
    • Plugin: A JavaScript object with an apply property called by the webpack compiler, providing access to the entire compilation lifecycle to extend functionality.
    • Loader: Transformations applied to source code during the require() or import process, acting similarly to a task-runner to pre-process files.
    • Target: The deployment environment (e.g., browser, node, electron) for which webpack compiles the code.

    Optimization and Loading

    • Code Splitting: Dividing code into various bundles/chunks that can be loaded on demand.
    • Bundle Splitting: An optimization technique that generates multiple bundles for a single application to improve caching and reduce re-downloading.
    • Lazy Loading: The process of loading application chunks only when they are actually needed.
    • Tree Shaking: The elimination of unused/dead code by analyzing import statements to determine which parts of dependencies are actually utilized.
    • Hot Module Replacement (HMR): A process that exchanges, adds, or removes modules in a running application without requiring a full page reload.
    • Shimming: The process of making non-module or unsupported module formats compatible with webpack.

    Module Management

    • Module Resolution: The process of locating a module by its absolute path, typically searching directories specified in resolve.modules.
    • Request: The expression used in a require or import statement (e.g., ./template/file.js).
    • Manifest: A runtime file used to resolve and load modules once they have been bundled and shipped to the browser.
  5. Explore Webpack Plugins

    main

    Plugins extend Webpack's capabilities by performing tasks during the bundling process. Common use cases include:

    • Asset Management: HTML Webpack Plugin for HTML generation, Copy Webpack Plugin for file copying, and Mini css extract plugin for CSS extraction.
    • Optimization & Analysis: Bundle Analyzer for visualizing bundle size, Compression Plugin for content encoding, and Duplicate Package Checker to find redundant packages.
    • Environment & Constants: DefinePlugin for compile-time constants and Dotenv Webpack for environment variables.
    • Development & DX: Build Notifier Plugin for OS notifications, ESLint Webpack Plugin for linting, and Stylelint Webpack Plugin for CSS linting.
    • Specialized Tasks: Serverless Webpack for Lambda bundling, Prerender SPA for static site generation, and CycloneDX Webpack Plugin for generating SBOMs.
  6. Explore the Webpack Ecosystem and Community

    main
    The Webpack ecosystem includes various resources for support, community discussion, and learning. You can find technical help on StackOverflow, read articles on Medium, or join real-time discussions on Gitter Chat. Additionally, you can support the ongoing development of Webpack via Open Collective.
  7. What is Hot Module Replacement (HMR)?

    main

    Hot Module Replacement (HMR) is a feature that allows the exchange, addition, or removal of modules while an application is running, without requiring a full page reload.

    Key benefits include:

    • Retaining application state: Avoid losing transient UI state (like form inputs or open modals) that is lost during a full reload.
    • Development speed: Only the changed parts of the application are updated.
    • Instant CSS/JS updates: Modifications to styles or logic appear almost instantly in the browser, similar to using browser dev tools.
  8. What is a webpack Module

    main

    In webpack, a module is any file in your project. Unlike Node.js modules which are primarily JavaScript-based, webpack applies the concept of modules to any file type by treating them as discrete chunks of functionality with defined dependencies.

    Webpack can resolve dependencies expressed in various ways, including:

    • ES2015 import statements
    • CommonJS require() statements
    • AMD define and require statements
    • CSS/Sass/Less @import statements
    • Image URLs within stylesheets url(...) or HTML <img src=...> files.
  9. What is webpack and why use it

    main

    webpack is a module bundler designed to manage JavaScript applications and their assets. It solves the limitations of manual script loading (network bottlenecks) and large monolithic files (scope collisions and maintainability issues).

    Key capabilities include:

    • Module Support: Bundles both ECMAScript Modules (ESM) and CommonJS modules.
    • Automatic Dependency Collection: Unlike task runners that require manual dependency declaration, webpack automatically builds and infers a dependency graph based on your import and export statements.
    • Asset Management: Through the use of plugins and loaders, webpack can handle non-JavaScript assets like images, fonts, and stylesheets.
    • Performance Optimizations: Supports advanced features like async chunk loading and prefetching to improve load times.
  10. How webpack plugins work with Tapable

    main

    Webpack's plugin system is built on tapable, a utility that allows plugins to hook into key events during the compilation process. Most core webpack objects (like the compiler) extend the Tapable class.

    To inject custom logic, plugins use one of three primary methods to 'tap' into a hook, depending on the hook's type:

    1. tap: Used for synchronous hooks (SyncHook).
    2. tapAsync: Used for asynchronous hooks, requiring a callback to signal completion.
    3. tapPromise: Used for asynchronous hooks, accepting a function that returns a Promise.

    The specific methods available to you depend on the underlying hook type defined for that specific event (e.g., compile might only support synchronous tapping, while run might support all three).

    // Synchronous tap
    compiler.hooks.compile.tap("MyPlugin", (params) => {
      console.log("Synchronously tapping the compile hook.");
    });
    
    // Asynchronous tap with callback
    compiler.hooks.run.tapAsync(
      "MyPlugin",
      (source, target, routesList, callback) => {
        console.log("Asynchronously tapping the run hook.");
        callback();
      },
    );
    
    // Asynchronous tap with Promise
    compiler.hooks.run.tapPromise("MyPlugin", (source, target, routesList) =>
      new Promise((resolve) => {
        setTimeout(resolve, 1000);
      }).then(() => {
        console.log("Asynchronously tapping the run hook with a delay.");
      }),
    );
  11. Mixing ES2015, AMD, and CommonJS modules

    main

    Webpack allows you to mix ES2015, AMD, and CommonJS module types within the same file.

    • When a CommonJS module requires an ES2015 module, the ES2015 default export maps to the required object.
    • When an ES2015 module imports a CommonJS module, module.exports maps to the default import, and named exports are read from the returned object.
    // CommonJS consuming ES2015 Module
    const book = require("./book");
    book.currentPage;
    book.default === "This is a book";
    
    // ES2015 Module consuming CommonJS
    import fs from "node:fs"; // module.exports map to default
    import { readFileSync } from "node:fs"; // named exports are read from returned object