JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

How do I bundle JavaScript applications with Webpack?

Asked on Sep 16, 2024

Answer

Webpack is a popular module bundler for JavaScript applications, allowing you to compile JavaScript modules into a single file or a few files. Here's a basic example of how to set up Webpack for a JavaScript project.
<!-- BEGIN COPY / PASTE -->
        // Step 1: Install Webpack and Webpack CLI
        // Run this command in your terminal
        npm install --save-dev webpack webpack-cli

        // Step 2: Create a basic Webpack configuration file (webpack.config.js)
        const path = require('path');

        module.exports = {
            entry: './src/index.js', // Entry point of your application
            output: {
                filename: 'bundle.js', // Output bundle file
                path: path.resolve(__dirname, 'dist') // Output directory
            },
            mode: 'development' // Set mode to 'development' or 'production'
        };

        // Step 3: Add a script to your package.json to run Webpack
        // "scripts": {
        //   "build": "webpack"
        // }

        // Step 4: Run Webpack to bundle your application
        // Run this command in your terminal
        npm run build
        <!-- END COPY / PASTE -->
Additional Comment:
  1. Install Webpack and Webpack CLI using npm to manage your project's dependencies.
  2. Create a "webpack.config.js" file to define the entry point, output file, and mode (development or production).
  3. Add a build script to your "package.json" to easily run Webpack from the command line.
  4. Execute "npm run build" to bundle your JavaScript files into a single output file, "bundle.js", located in the "dist" directory.
  • Ensure your project structure includes a "src" directory with an "index.js" file as the entry point.
  • Adjust the Webpack configuration as needed for more complex setups, such as handling CSS, images, or using Babel for transpilation.
✅ Answered with JavaScript best practices.
← Back to All Questions