### Interactive create-webpack-app Setup Example Source: https://webpack.js.org/blog/2026-04-08-webpack-5-106 An example of the interactive prompts during `create-webpack-app` setup, allowing customization of project features like TypeScript, dev server, PWA support, and CSS solutions. ```bash $ npx create-webpack-app ? Which of the following JS solutions do you want to use? Typescript ? Do you want to use webpack-dev-server? Yes ? Do you want to simplify the creation of HTML files for your bundle? Yes ? Do you want to add PWA support? No ? Which of the following CSS solutions do you want to use? CSS only ? Will you be using PostCSS in your project? Yes ? Do you want to extract CSS for every file? Only for Production ? Which package manager do you want to use? npm [create-webpack] ℹ️ Initializing a new Webpack project... [create-webpack] ✅ Project dependencies installed successfully! ``` -------------------------------- ### Start Webpack Dev Server Programmatically Source: https://webpack.js.org/api/printable Configure and start the Webpack development server using its Node.js API. This example demonstrates setting up the compiler, server options, and initiating the server. ```javascript import webpack from "webpack"; import WebpackDevServer from "webpack-dev-server"; import webpackConfig from "./webpack.config.js"; const compiler = webpack(webpackConfig); const devServerOptions = { ...webpackConfig.devServer, open: true }; const server = new WebpackDevServer(devServerOptions, compiler); const runServer = async () => { console.log("Starting server..."); await server.start(); }; runServer(); ``` -------------------------------- ### http-server Output Example Source: https://webpack.js.org/guides/printable Shows the typical console output when starting the http-server to serve the 'dist' directory. It indicates the available network addresses and ports. ```bash > http-server dist Starting up http-server, serving dist Available on: http://xx.x.x.x:8080 http://127.0.0.1:8080 http://xxx.xxx.x.x:8080 Hit CTRL-C to stop the server ``` -------------------------------- ### Start the webpack-dev-server using start() Source: https://webpack.js.org/api/webpack-dev-server Use the `start()` method to initiate the webpack-dev-server instance. This method is asynchronous and requires awaiting. ```javascript import webpack from "webpack"; import WebpackDevServer from "webpack-dev-server"; import webpackConfig from "./webpack.config.js"; const compiler = webpack(webpackConfig); const devServerOptions = { ...webpackConfig.devServer, open: true }; const server = new WebpackDevServer(devServerOptions, compiler); const runServer = async () => { console.log("Starting server..."); await server.start(); }; runServer(); ``` -------------------------------- ### start Source: https://webpack.js.org/api/webpack-dev-server Starts the webpack-dev-server instance. This method is asynchronous and should be awaited. ```APIDOC ## start It instructs `webpack-dev-server` instance to start the server. ### Method async ### Example ```javascript import webpack from "webpack"; import WebpackDevServer from "webpack-dev-server"; import webpackConfig from "./webpack.config.js"; const compiler = webpack(webpackConfig); const devServerOptions = { ...webpackConfig.devServer, open: true }; const server = new WebpackDevServer(devServerOptions, compiler); const runServer = async () => { console.log("Starting server..."); await server.start(); }; runServer(); ``` ``` -------------------------------- ### http-server output example Source: https://webpack.js.org/guides/progressive-web-application This is the expected output when running 'npm run build' followed by 'npm start'. It indicates that http-server is running and serving files from the 'dist' directory. ```bash > http-server dist Starting up http-server, serving dist Available on: http://xx.x.x.x:8080 http://127.0.0.1:8080 http://xxx.xxx.x.x:8080 Hit CTRL-C to stop the server ``` -------------------------------- ### Basic Web Worker Example Source: https://webpack.js.org/guides/web-workers Demonstrates a simple Webpack setup for Web Workers, including sending a message to the worker and receiving a response. ```javascript const worker = new Worker(new URL("./deep-thought.js", import.meta.url)); worker.postMessage({ question: "The Answer to the Ultimate Question of Life, The Universe, and Everything.", }); worker.onmessage = ({ data: { answer } }) => { console.log(answer); }; ``` -------------------------------- ### Start Developing a New Webpack Project Source: https://webpack.js.org/blog/2026-04-08-webpack-5-106 After scaffolding a new project with `create-webpack-app`, navigate into the project directory and start the development server using `npm start`. ```bash cd my-project npm start ``` -------------------------------- ### Output Webpack System Information with Additional Package Source: https://webpack.js.org/api/cli Example of getting webpack system information and including details for the 'postcss' package. ```bash npx webpack info --additional-package postcss ``` -------------------------------- ### Install MiniCssExtractPlugin Source: https://webpack.js.org/plugins/mini-css-extract-plugin Install the plugin using npm, yarn, or pnpm. ```bash npm install --save-dev mini-css-extract-plugin ``` ```bash yarn add -D mini-css-extract-plugin ``` ```bash pnpm add -D mini-css-extract-plugin ``` -------------------------------- ### Install istanbul-instrumenter-loader Source: https://webpack.js.org/loaders/istanbul-instrumenter-loader Install the istanbul-instrumenter-loader as a development dependency. ```bash npm i -D istanbul-instrumenter-loader ``` -------------------------------- ### Install sharp Source: https://webpack.js.org/plugins/image-minimizer-webpack-plugin Install the sharp package as a development dependency. ```bash npm install sharp --save-dev ``` -------------------------------- ### Example Module Definition Source: https://webpack.js.org/loaders/expose-loader This is an example of a local module that can be exposed. ```javascript function method1() { console.log("method1"); } function method2() { console.log("method1"); } export { method1, method2 }; ``` -------------------------------- ### Install CompressionWebpackPlugin Source: https://webpack.js.org/plugins/compression-webpack-plugin Install the plugin using npm, yarn, or pnpm. ```bash npm install compression-webpack-plugin --save-dev ``` ```bash yarn add -D compression-webpack-plugin ``` ```bash pnpm add -D compression-webpack-plugin ``` -------------------------------- ### Install Webpack Source: https://webpack.js.org/guides/printable Install webpack and webpack-dev-server as development dependencies. ```bash npm install --save-dev webpack/webpack# ``` -------------------------------- ### Installation Source: https://webpack.js.org/plugins/compression-webpack-plugin Install the CompressionWebpackPlugin using npm, yarn, or pnpm. ```APIDOC ## Installation To begin, you'll need to install `compression-webpack-plugin`: ```bash npm install compression-webpack-plugin --save-dev ``` or ```bash yarn add -D compression-webpack-plugin ``` or ```bash pnpm add -D compression-webpack-plugin ``` ``` -------------------------------- ### Install mini-css-extract-plugin Source: https://webpack.js.org/plugins/printable Install the plugin using npm, yarn, or pnpm. ```bash npm install --save-dev mini-css-extract-plugin ``` ```bash yarn add -D mini-css-extract-plugin ``` ```bash pnpm add -D mini-css-extract-plugin ``` -------------------------------- ### Install CopyWebpackPlugin Source: https://webpack.js.org/plugins/copy-webpack-plugin Install the plugin using npm, yarn, or pnpm. ```bash npm install copy-webpack-plugin --save-dev ``` ```bash yarn add -D copy-webpack-plugin ``` ```bash pnpm add -D copy-webpack-plugin ``` -------------------------------- ### Install imagemin Source: https://webpack.js.org/plugins/image-minimizer-webpack-plugin Install the plugin along with the imagemin package for image optimization. ```bash npm install image-minimizer-webpack-plugin imagemin --save-dev ``` -------------------------------- ### BannerPlugin Usage Examples Source: https://webpack.js.org/plugins/banner-plugin Examples demonstrating how to use the BannerPlugin with different configurations. ```APIDOC ## BannerPlugin Usage Examples ### Description Provides practical examples of how to implement the BannerPlugin with various settings. ### Request Example ```javascript // Using a string banner new webpack.BannerPlugin({ banner: "hello world", }); // Using a function banner new webpack.BannerPlugin({ banner: (yourVariable) => `yourVariable: ${yourVariable}`, }); // Adding a raw banner at a specific compilation stage new webpack.BannerPlugin({ raw: true, banner: "/* banner is a string */", stage: webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT, }); ``` ``` -------------------------------- ### Build Command for Version A Source: https://webpack.js.org/plugins/normal-module-replacement-plugin Example command to build the application targeting VERSION_A, demonstrating how to pass environment variables. ```bash npx webpack --env APP_TARGET=VERSION_A ``` -------------------------------- ### Install Development Dependencies Source: https://webpack.js.org/guides/development Install express and webpack-dev-middleware as development dependencies for custom server setups. ```bash npm install --save-dev express webpack-dev-middleware ``` -------------------------------- ### Configure Implementation Options Source: https://webpack.js.org/plugins/image-minimizer-webpack-plugin Demonstrates how to pass specific options to the chosen image implementation. This example uses `sharpMinify` and sets JPEG quality. ```javascript const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin"); module.exports = { optimization: { minimizer: [ "...", new ImageMinimizerPlugin({ generator: [ { preset: "name", implementation: ImageMinimizerPlugin.sharpMinify, // Options options: { encodeOptions: { jpeg: { quality: 90, }, }, }, }, ], }), ], }, }; ``` -------------------------------- ### Start and Stop Server Source: https://webpack.js.org/api/printable Starts the webpack-dev-server and then stops it after a specified delay. Requires webpack and webpack-dev-server to be installed. ```javascript import webpack from "webpack"; import WebpackDevServer from "webpack-dev-server"; import webpackConfig from "./webpack.config.js"; const compiler = webpack(webpackConfig); const devServerOptions = { ...webpackConfig.devServer, open: true }; const server = new WebpackDevServer(devServerOptions, compiler); const runServer = async () => { console.log("Starting server..."); await server.start(); }; const stopServer = async () => { console.log("Stopping server..."); await server.stop(); }; runServer(); setTimeout(stopServer, 5000); ``` -------------------------------- ### Configuration File for Version A Source: https://webpack.js.org/plugins/normal-module-replacement-plugin Example configuration file for a specific application version (VERSION_A). ```javascript export default { title: "I am version A", }; ``` -------------------------------- ### startCallback Source: https://webpack.js.org/api/webpack-dev-server Starts the webpack-dev-server instance and executes a callback function upon successful start. ```APIDOC ## startCallback(callback) It instructs `webpack-dev-server` instance to start the server and then run the callback function. ### Parameters #### Path Parameters - **callback** (function) - Required - The function to execute after the server starts. ### Example ```javascript import webpack from "webpack"; import WebpackDevServer from "webpack-dev-server"; import webpackConfig from "./webpack.config.js"; const compiler = webpack(webpackConfig); const devServerOptions = { ...webpackConfig.devServer, open: true }; const server = new WebpackDevServer(devServerOptions, compiler); server.startCallback(() => { console.log("Successfully started server on http://localhost:8080"); }); ``` ``` -------------------------------- ### Get Webpack Version Source: https://webpack.js.org/contribute/writing-a-scaffold Run this command to check the installed versions of Webpack and related tools. ```bash npx webpack version ``` -------------------------------- ### Webpack Build Output Example Source: https://webpack.js.org/guides/code-splitting-async Illustrates the build output after configuring multiple entry points, showing the creation of separate bundle files for each entry. ```text asset index.bundle.js 553 KiB [emitted] (name: index) asset another.bundle.js 553 KiB [emitted] (name: another) runtime modules 2.49 KiB 12 modules cacheable modules 530 KiB ./src/index.js 257 bytes [built] [code generated] ./src/another-module.js 84 bytes [built] [code generated] ./node_modules/lodash/lodash.js 530 KiB [built] [code generated] webpack 5.x.x compiled successfully in 245 ms ``` -------------------------------- ### Starting Webpack Dev Server with Custom WebSocket URL Source: https://webpack.js.org/guides/printable Start the webpack-dev-server with a specific client WebSocket URL and enable polling for file changes. This command is used in conjunction with the nginx proxy setup. ```bash webpack serve --client-web-socket-url ws://10.10.10.61:8080/ws --watch-options-poll ``` -------------------------------- ### Output Webpack System Information in Markdown Source: https://webpack.js.org/api/cli Example of getting webpack system information formatted as markdown. ```bash npx webpack info --output markdown ``` -------------------------------- ### Get Internal IP Addresses Source: https://webpack.js.org/api/printable Asynchronously retrieves and logs the local IPv4 and IPv6 addresses. Requires webpack-dev-server to be installed. ```javascript import WebpackDevServer from "webpack-dev-server"; const logInternalIPs = async () => { const localIPv4 = await WebpackDevServer.internalIP("v4"); const localIPv6 = await WebpackDevServer.internalIP("v6"); console.log("Local IPv4 address:", localIPv4); console.log("Local IPv6 address:", localIPv6); }; logInternalIPs(); ``` -------------------------------- ### Specify Multiple Entry Points Source: https://webpack.js.org/api/cli This example demonstrates how to specify multiple entry points for your project directly from the command line. ```bash npx webpack --entry ./first.js --entry ./second.js --output-path /build ``` -------------------------------- ### Run Webpack Dev Server with Static Files and Open Source: https://webpack.js.org/api/cli Example of running the webpack dev server, enabling static file serving and automatically opening the default browser. ```bash npx webpack serve --static --open ``` -------------------------------- ### Documentation Assumption Correction Source: https://webpack.js.org/contribute/writers-guide Example showing how to rephrase documentation to avoid assuming prior knowledge and instead link to relevant guides. ```diff - You might already know how to optimize bundle for production... + As we've learned in [production guide](/guides/production/)... ``` -------------------------------- ### Initialize New Webpack Project with Options Source: https://webpack.js.org/api/cli Example of initializing a new webpack project with a specific path, forcing the generation, and using the default template. ```bash npx create-webpack-app ./my-app --force --template=default ``` -------------------------------- ### Example Module Import Source: https://webpack.js.org/loaders/expose-loader This is an example of how a local module might be imported in your application. ```javascript import { method1 } from "./my-module.js"; ``` -------------------------------- ### Start the webpack-dev-server using startCallback() Source: https://webpack.js.org/api/webpack-dev-server Use the `startCallback()` method to start the server and execute a callback function upon successful startup. ```javascript import webpack from "webpack"; import WebpackDevServer from "webpack-dev-server"; import webpackConfig from "./webpack.config.js"; const compiler = webpack(webpackConfig); const devServerOptions = { ...webpackConfig.devServer, open: true }; const server = new WebpackDevServer(devServerOptions, compiler); server.startCallback(() => { console.log("Successfully started server on http://localhost:8080"); }); ``` -------------------------------- ### Minimal webpack.config.js Source: https://webpack.js.org/guides/development-vagrant A basic webpack configuration file to get started. It sets the context to the current directory and specifies the entry point for the application. ```javascript import path from "node:path"; import { fileURLToPath } from "node:url"; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); export default { context: __dirname, entry: "./app.js", }; ``` -------------------------------- ### Avoiding Simplistic Language Source: https://webpack.js.org/contribute/writers-guide Example demonstrating how to replace simplistic phrasing like 'Simply run command...' with more direct instructions, specifying the command name. ```diff - Simply run command... + Run the `command-name` command... ``` -------------------------------- ### Initialize New Webpack Project Source: https://webpack.js.org/configuration/printable Use `npx create-webpack-app` to quickly set up a new webpack project with a guided configuration process. ```bash npx create-webpack-app [command] [options] ``` -------------------------------- ### Dev Server Output Messages Source: https://webpack.js.org/configuration/printable Example output messages displayed when the webpack-dev-server starts, indicating the project's running status and network accessibility. ```text [webpack-dev-server] Project is running at: [webpack-dev-server] Loopback: http://localhost:9000/ [webpack-dev-server] On Your Network (IPv4): http://197.158.164.104:9000/ [webpack-dev-server] On Your Network (IPv6): http://[fe80::1]:9000/ [webpack-dev-server] Content not from webpack is served from '/path/to/public' directory ``` -------------------------------- ### Build Command for Version B Source: https://webpack.js.org/plugins/normal-module-replacement-plugin Example command to build the application targeting VERSION_B, demonstrating how to pass environment variables. ```bash npx webpack --env APP_TARGET=VERSION_B ``` -------------------------------- ### Basic webpack.config.js Setup Source: https://webpack.js.org/loaders/postcss-loader Configure webpack to use postcss-loader along with style-loader and css-loader for processing CSS files. This example includes the 'postcss-preset-env' plugin. ```javascript import css from "file.css"; ``` ```javascript module.exports = { module: { rules: [ { test: /\.css$/i, use: [ "style-loader", "css-loader", { loader: "postcss-loader", options: { postcssOptions: { plugins: [ [ "postcss-preset-env", { // Options }, ], ], }, }, }, ], }, ], }, }; ``` -------------------------------- ### Modifying Module Build with buildModule Hook Source: https://webpack.js.org/api/printable Use the `buildModule` hook to modify a module before its build starts. This example sets `module.useSourceMap` to true for a specific plugin. ```javascript compilation.hooks.buildModule.tap( "SourceMapDevToolModuleOptionsPlugin", (module) => { module.useSourceMap = true; }, ); ``` -------------------------------- ### Project Structure for Code Splitting Demo Source: https://webpack.js.org/guides/code-splitting Illustrates the project file structure for a basic code splitting example using entry points. ```text webpack-demo ├── package.json ├── package-lock.json ├── webpack.config.js ├── /dist ├── /src │ ├── index.js + │ └── another-module.js └── /node_modules ``` -------------------------------- ### CLI Usage for Dev Server Options Source: https://webpack.js.org/configuration/dev-server Demonstrates how to use CLI commands to configure dev server options like `allowedHosts`, `bonjour`, `client-logging`, `client-overlay`, and `client-progress`. ```bash npx webpack serve --allowed-hosts .host.com --allowed-hosts host2.com ``` ```bash npx webpack serve --allowed-hosts all ``` ```bash npx webpack serve --allowed-hosts auto ``` ```bash npx webpack serve --bonjour ``` ```bash npx webpack serve --no-bonjour ``` ```bash npx webpack serve --client-logging info ``` ```bash npx webpack serve --client-overlay ``` ```bash npx webpack serve --no-client-overlay ``` ```bash npx webpack serve --client-overlay-errors --no-client-overlay-warnings --client-overlay-runtime-errors ``` ```bash npx webpack serve --client-progress ``` ```bash npx webpack serve --no-client-progress ``` -------------------------------- ### Output Webpack System Information in JSON with Additional Package Source: https://webpack.js.org/api/cli Example of getting webpack system information in JSON format, including details for the 'postcss' package. ```bash npx webpack info --output json --addition-package postcss ``` -------------------------------- ### Wildcard Alias Configuration Source: https://webpack.js.org/configuration/printable Use wildcards (*) in alias keys to map patterns of module imports to corresponding paths. This example maps imports starting with '@' to a 'src/' directory. ```javascript import path from "node:path"; import { fileURLToPath } from "node:url"; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); export default { // ... resolve: { alias: { "@*": path.resolve(__dirname, "src/*"), // maps @something to path/to/something }, }, }; ``` -------------------------------- ### Custom Webpack Plugin Example Source: https://webpack.js.org/concepts/printable A basic custom Webpack plugin that logs a message when the build process starts. It uses the 'run' hook and a constant for the plugin name. ```javascript const pluginName = "ConsoleLogOnBuildWebpackPlugin"; class ConsoleLogOnBuildWebpackPlugin { apply(compiler) { compiler.hooks.run.tap(pluginName, (compilation) => { console.log("The webpack build process is starting!"); }); } } export default ConsoleLogOnBuildWebpackPlugin; ``` -------------------------------- ### Configuration File for Version B Source: https://webpack.js.org/plugins/normal-module-replacement-plugin Example configuration file for a specific application version (VERSION_B). ```javascript export default { title: "I am version B", }; ``` -------------------------------- ### Basic Entry Description Configuration Source: https://webpack.js.org/concepts/printable Demonstrates a valid configuration using `dependOn` to establish entry point dependencies. Ensure dependent entry points are loaded before the current one. ```javascript export default { entry: { a2: "dependingfile.js", b2: { dependOn: "a2", import: "./src/app.js", }, }, }; ``` -------------------------------- ### Modify Module Build with buildModule Hook Source: https://webpack.js.org/api/compilation-hooks Use the `buildModule` hook to modify module properties before the build starts. This example sets `useSourceMap` to true for a specific plugin. ```javascript compilation.hooks.buildModule.tap( "SourceMapDevToolModuleOptionsPlugin", (module) => { module.useSourceMap = true; }, ); ``` -------------------------------- ### Multiple Minimizers Example Source: https://webpack.js.org/plugins/image-minimizer-webpack-plugin Shows how to configure multiple minimizers to handle different image types. This setup allows `sharp` to process bitmaps and `svgo` to process SVGs. ```javascript const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin"); module.exports = { optimization: { minimizer: [ "...", new ImageMinimizerPlugin({ minimizer: [ { // `sharp` will handle all bitmap formats (JPG, PNG, GIF, ...) implementation: ImageMinimizerPlugin.sharpMinify, // exclude SVG if implementation support it. Not required for `sharp`. // filter: (source, sourcePath) => !(/\.(svg)$/i.test(sourcePath)), options: { encodeOptions: { // Your options for `sharp` // https://sharp.pixelplumbing.com/api-output }, }, }, { // `svgo` will handle vector images (SVG) implementation: ImageMinimizerPlugin.svgoMinify, options: { encodeOptions: { // Pass over SVGs multiple times to ensure all optimizations are applied. False by default multipass: true, plugins: [ // set of built-in plugins enabled by default // see: https://github.com/svg/svgo#default-preset "preset-default", ], }, }, }, ], }), ], }, }; ``` -------------------------------- ### Install Webpack and Webpack CLI Source: https://webpack.js.org/get-started Initialize your project with npm/yarn/pnpm, then install webpack and webpack-cli as development dependencies. Choose one package manager. ```bash # npm npm init -y npm install webpack webpack-cli --save-dev ``` ```bash # yarn yarn init -y yarn add webpack webpack-cli --dev ``` ```bash # pnpm pnpm init pnpm add webpack webpack-cli -D ``` -------------------------------- ### Build remote HTTP resources with Webpack Source: https://webpack.js.org/configuration/experiments When `experiments.buildHttp` is enabled, Webpack can process remote resources starting with `http(s):` as if they were local modules. This example shows importing a module from a CDN. ```javascript // src/index.js import pMap1 from "https://cdn.skypack.dev/p-map"; // with `buildHttp` enabled, webpack will build pMap1 like a regular local module console.log(pMap1); ``` -------------------------------- ### Example entry.js for EnvironmentPlugin Source: https://webpack.js.org/plugins/environment-plugin This is a sample entry file that uses environment variables configured by EnvironmentPlugin. ```javascript if (process.env.NODE_ENV === "production") { console.log("Welcome to production"); } if (process.env.DEBUG) { console.log("Debugging output"); } ``` -------------------------------- ### Configure Roots for Server-Relative URL Resolution Source: https://webpack.js.org/loaders/html-loader Use `resolve.roots` in webpack.config.js to specify directories where server-relative URLs (starting with '/') are resolved. This example shows resolving '/image.jpg' from the 'fixtures' directory. ```javascript module.exports = { context: __dirname, module: { rules: [ { test: /\.html$/i, loader: "html-loader", options: {}, }, { test: /\.jpg$/, type: "asset/resource", }, ], }, resolve: { roots: [path.resolve(__dirname, "fixtures")], }, }; ``` ```html ``` ```javascript // => image.jpg in __dirname/fixtures will be resolved ``` -------------------------------- ### Install sharp Source: https://webpack.js.org/plugins/image-minimizer-webpack-plugin Install the plugin along with the sharp package for high-performance image processing. ```bash npm install image-minimizer-webpack-plugin sharp --save-dev ``` -------------------------------- ### Deprecated babel loader notation Source: https://webpack.js.org/loaders/printable Example of the deprecated short notation for babel-loader in webpack configurations prior to version 2.x, which can lead to errors if the 'babel' npm package is installed instead of 'babel-loader'. ```javascript { test: /\.(?:js|mjs|cjs)$/, loader: 'babel', } ``` -------------------------------- ### Scaffold New Webpack Projects with create-webpack-app Source: https://webpack.js.org/blog/2026-04-08-webpack-5-106 Use `npx create-webpack-app` to scaffold a new webpack project interactively. This command replaces the older `webpack init` from `webpack-cli` and guides you through project setup. ```bash npx create-webpack-app ``` -------------------------------- ### Get Compilation Stats as JSON (Custom Options) Source: https://webpack.js.org/api/node Retrieves compilation information as a JSON object with custom options to control the output detail. For example, disabling asset information while enabling hash reporting. ```javascript stats.toJson({ assets: false, hash: true, }); ``` -------------------------------- ### Example Package Structure Source: https://webpack.js.org/guides/tree-shaking Illustrates a typical file structure for a UI component library package, including JavaScript components and their associated CSS files. ```text awesome-ui/ ├── package.json └── dist/ ├── index.js ├── components/ │ ├── index.js │ ├── Button/ │ │ ├── index.js │ │ └── Button.css │ ├── Card/ │ │ ├── index.js │ │ └── Card.css │ └── Modal/ │ ├── index.js │ └── Modal.css └── theme/ ├── index.js └── defaultTheme.css ``` -------------------------------- ### Install Webpack and Dependencies Source: https://webpack.js.org/guides/author-libraries Initialize npm project and install webpack, webpack-cli, and lodash as development dependencies. ```bash npm init -y npm install --save-dev webpack webpack-cli lodash ``` -------------------------------- ### Get Webpack System Info Source: https://webpack.js.org/contribute/writing-a-scaffold Outputs information about your system and webpack installation. Use --output json or --output markdown for specific formats, and --additional-package to include details about other packages like postcss. ```bash npx webpack info [options] ``` ```bash npx webpack info --output json --addition-package postcss ``` ```bash npx webpack info --additional-package postcss ``` ```bash npx webpack info --output markdown ``` -------------------------------- ### Install Development Dependencies Source: https://webpack.js.org/guides/development-vagrant Install webpack, webpack-cli, @webpack-cli/serve, and webpack-dev-server using npm. ```bash npm install --save-dev webpack webpack-cli @webpack-cli/serve webpack-dev-server ``` -------------------------------- ### Install CSS Minimizer Dependencies Source: https://webpack.js.org/plugins/printable Install the necessary peer dependencies for the chosen CSS minimizer. Only install the ones you intend to use. ```bash npm install --save-dev cssnano postcss # or npm install --save-dev csso # or npm install --save-dev clean-css # or npm install --save-dev esbuild # or npm install --save-dev lightningcss # or npm install --save-dev @swc/css ``` -------------------------------- ### Expose Library via 'window' Assignment Source: https://webpack.js.org/configuration/output Demonstrates assigning the entry point's return value to `globalThis.MyLibrary`, making it accessible on the global scope. ```javascript globalThis.MyLibrary = _entry_return_; globalThis.MyLibrary.doSomething(); ``` -------------------------------- ### Install whatwg-fetch polyfill Source: https://webpack.js.org/guides/shimming Install the `whatwg-fetch` polyfill using npm. This polyfill provides a modern Fetch API implementation for environments that do not natively support it. ```bash npm install --save whatwg-fetch ``` -------------------------------- ### Using Library with AMD Source: https://webpack.js.org/guides/author-libraries Example of how a library can be consumed using AMD module syntax. ```javascript require(["webpackNumbers"], (webpackNumbers) => { // ... webpackNumbers.wordToNum("Two"); }); ``` -------------------------------- ### Get Verbose Help Source: https://webpack.js.org/api/cli Use this command to list all supported commands and flags provided by the CLI. ```bash npx webpack --help=verbose ``` -------------------------------- ### Entry Script with Fetch API Source: https://webpack.js.org/guides/printable Demonstrates using the Fetch API within the main entry script. This example assumes polyfills are handled separately. ```javascript function component() { const element = document.createElement('div'); element.innerHTML = join(['Hello', 'webpack'], ' '); // Assume we are in the context of `window` this.alert("Hmmm, this probably isn't a great idea..."); return element; } document.body.appendChild(component()); fetch('https://jsonplaceholder.typicode.com/users') .then((response) => response.json()) .then((json) => { console.log( "We retrieved some data! AND we're confident it will work on a variety of browser distributions." ); console.log(json); }) .catch((error) console.error('Something went wrong when fetching this data: ', error) ); ``` -------------------------------- ### Install tsconfig-paths Source: https://webpack.js.org/configuration/printable Install the tsconfig-paths package as a development dependency. ```bash npm install --save-dev tsconfig-paths ``` -------------------------------- ### Build Webpack with Specific Config and Stats Source: https://webpack.js.org/api/cli Example of running the build command with a specified configuration file and verbose stats output. ```bash npx webpack build --config ./webpack.config.js --stats verbose ``` -------------------------------- ### Get Basic Help Source: https://webpack.js.org/api/cli Use this command to list basic commands and flags available on the CLI. Both `webpack help [command] [option]` and `webpack [command] --help` are valid syntaxes. ```bash npx webpack --help ``` ```bash # or npx webpack help ``` -------------------------------- ### Webpack Build Output Example Source: https://webpack.js.org/guides/asset-management Example of the compilation output after running the webpack build command, showing assets and modules processed. ```bash $ npm run build ... [webpack-cli] Compilation finished asset bundle.js 72.6 KiB [emitted] [minimized] (name: main) 1 related asset runtime modules 1000 bytes 5 modules orphan modules 326 bytes [orphan] 1 module cacheable modules 539 KiB modules by path ./node_modules/ 538 KiB ./node_modules/lodash/lodash.js 530 KiB [built] [code generated] ./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js 6.67 KiB [built] [code generated] ./node_modules/css-loader/dist/runtime/api.js 1.57 KiB [built] [code generated] modules by path ./src/ 965 bytes ./src/index.js + 1 modules 639 bytes [built] [code generated] ./node_modules/css-loader/dist/cjs.js!./src/style.css 326 bytes [built] [code generated] webpack 5.x.x compiled successfully in 2231 ms ``` -------------------------------- ### Install url-loader Source: https://webpack.js.org/loaders/url-loader Install the url-loader package as a development dependency. ```bash $ npm install url-loader --save-dev ``` -------------------------------- ### Run webpack-dev-server Source: https://webpack.js.org/guides/development-vagrant Start the webpack development server, making it accessible from the host machine and enabling file watching with polling. ```bash webpack serve --host 0.0.0.0 --client-web-socket-url ws://10.10.10.61:8080/ws --watch-options-poll ``` -------------------------------- ### YAML Data Example Source: https://webpack.js.org/guides/asset-management Example YAML file content. ```yaml title: YAML Example owner: name: Tom Preston-Werner organization: GitHub bio: |- GitHub Cofounder & CEO Likes tater tots and beer. dob: 1979-05-27T07:32:00.000Z ``` -------------------------------- ### Initialize a New Webpack Project Source: https://webpack.js.org/configuration Use `create-webpack-app` to quickly scaffold a new webpack project with your preferred configurations. This tool will prompt you for setup choices. ```bash npx create-webpack-app [command] [options] ``` ```bash $ npx create-webpack-app init Need to install the following packages: create-webpack-app@2.0.0 Ok to proceed? (y) ? Which of the following JS solutions do you want to use? Typescript ? Do you want to use webpack-dev-server? Yes ? Do you want to simplify the creation of HTML files for your bundle? Yes ? Do you want to add PWA support? No ? Which of the following CSS solutions do you want to use? CSS only ? Will you be using PostCSS in your project? Yes ? Do you want to extract CSS for every file? Only for Production ? Which package manager do you want to use? npm [create-webpack] ℹ️ Initializing a new Webpack project ... ... ... [create-webpack] ✅ Project dependencies installed successfully! [create-webpack] ✅ Project has been initialised with webpack! ``` -------------------------------- ### TOML Data Example Source: https://webpack.js.org/guides/asset-management Example TOML file content. ```toml title = "TOML Example" [owner] name = "Tom Preston-Werner" organization = "GitHub" bio = "GitHub Cofounder & CEO\nLikes tater tots and beer." dob = 1979-05-27T07:32:00Z ``` -------------------------------- ### Less Example with Extend Source: https://webpack.js.org/loaders/less-loader A Less file demonstrating the use of the &:extend directive. ```less div { &:extend(.body1); } ``` -------------------------------- ### Installing JSON5 Parser for Webpack Source: https://webpack.js.org/configuration/configuration-languages This command installs the json5 package, which is required by webpack-cli to parse JSON5 configuration files. Install the necessary parser as a dev dependency. ```bash npm install --save-dev json5 ``` -------------------------------- ### Project Structure Example Source: https://webpack.js.org/guides/printable Illustrates a typical project structure for a webpack project, including source files, distribution directory, and configuration files. ```text webpack-demo ├── package.json ├── package-lock.json + ├── webpack.config.js ├── /dist │ └── index.html └── /src └── index.js ``` -------------------------------- ### Install postcss-loader and postcss Source: https://webpack.js.org/loaders/postcss-loader Install the necessary packages using npm, yarn, or pnpm. ```bash npm install --save-dev postcss-loader postcss ``` ```bash yarn add -D postcss-loader postcss ``` ```bash pnpm add -D postcss-loader postcss ``` -------------------------------- ### Install HtmlWebpackPlugin Source: https://webpack.js.org/guides/printable Install the HtmlWebpackPlugin as a development dependency using npm. ```bash npm install --save-dev html-webpack-plugin ```