← Back to webpack/webpack

How to Deploy & Use webpack/webpack

# Webpack Deployment & Usage Guide

A comprehensive guide for installing, configuring, and deploying applications using webpack, the JavaScript module bundler.

## 1. Prerequisites

Before installing webpack, ensure you have the following:

- **Node.js**: Active LTS version or higher (webpack 5 requires Node.js 10.13.0+)
- **Package Manager**: npm (bundled with Node.js) or Yarn 1.x/2.x/3.x
- **Git**: For cloning repositories (optional)
- **Browser Support**: Target browsers must be [ES5-compliant](https://kangax.github.io/compat-table/es5/) (IE8 and below are not supported)
  - For `import()` and `require.ensure()` support in older browsers, include a Promise polyfill

## 2. Installation

### Local Installation (Recommended)

Install webpack as a development dependency in your project:

```bash
# Using npm
npm install --save-dev webpack

# Using yarn
yarn add webpack --dev

Install the webpack CLI (required for command line usage):

npm install --save-dev webpack-cli

Optional: Development Server

For local development with hot reloading:

npm install --save-dev webpack-dev-server

Verify Installation

npx webpack --version

3. Configuration

Basic Configuration File

Create a webpack.config.js in your project root:

const path = require('path');

module.exports = {
  // Entry point(s)
  entry: './src/index.js',
  
  // Output configuration
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
    clean: true, // Clean output directory before emit
  },
  
  // Mode: 'development', 'production', or 'none'
  mode: 'development',
  
  // Module rules and loaders
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      },
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
      },
    ],
  },
  
  // Plugins
  plugins: [
    // Add plugins here, e.g., HtmlWebpackPlugin
  ],
  
  // Source maps for debugging
  devtool: 'source-map',
  
  // Development server configuration
  devServer: {
    static: './dist',
    hot: true,
    port: 8080,
  },
  
  // Optimization settings
  optimization: {
    splitChunks: {
      chunks: 'all',
    },
  },
};

Environment-Specific Configuration

Create separate configs for different environments:

webpack.config.prod.js

const { merge } = require('webpack-merge');
const common = require('./webpack.config.js');

module.exports = merge(common, {
  mode: 'production',
  devtool: 'source-map',
  optimization: {
    minimize: true,
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all',
        },
      },
    },
  },
});

Package.json Scripts

Add npm scripts to package.json:

{
  "scripts": {
    "build": "webpack --config webpack.config.prod.js",
    "dev": "webpack serve --open",
    "watch": "webpack --watch",
    "start": "webpack serve --mode development"
  }
}

4. Build & Run

Development Mode

Start the development server with hot module replacement:

npm run dev
# or
npx webpack serve --mode development

Watch mode (rebuilds on file changes without dev server):

npm run watch
# or
npx webpack --watch --mode development

Production Build

Create an optimized production bundle:

npm run build
# or
npx webpack --mode=production

Output will be generated in the dist/ directory (or your configured output path).

Advanced Build Options

Analyze bundle size:

npx webpack --profile --json > stats.json
# Then use webpack-bundle-analyzer
npx webpack-bundle-analyzer stats.json

Build with specific config:

npx webpack --config webpack.config.custom.js

Memory management for large builds:

node --max-old-space-size=4096 ./node_modules/.bin/webpack --mode=production

5. Deployment

Static Site Deployment

Since webpack generates static assets, deploy the dist/ folder to any static hosting service:

Netlify/Vercel

  1. Build your project: npm run build
  2. Deploy the dist/ folder:
    # Netlify CLI
    netlify deploy --prod --dir=dist
    
    # Vercel CLI
    vercel --prod
    

GitHub Pages

# Using gh-pages package
npm install --save-dev gh-pages
npx gh-pages -d dist

AWS S3 + CloudFront

aws s3 sync dist/ s3://your-bucket-name --delete
aws cloudfront create-invalidation --distribution-id YOUR_DIST_ID --paths "/*"

Server-Side Rendering (SSR)

For Node.js server deployment:

// webpack.config.server.js
const nodeExternals = require('webpack-node-externals');

module.exports = {
  target: 'node',
  externals: [nodeExternals()],
  entry: './server.js',
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'server.js',
  },
};

Build and run:

npx webpack --config webpack.config.server.js
node build/server.js

Code Splitting for Production

Ensure your deployment supports dynamic imports:

// Lazy load routes
const About = import(/* webpackChunkName: "about" */ './about.js');

Configure output for CDN hosting:

output: {
  publicPath: 'https://cdn.example.com/assets/',
  filename: '[name].[contenthash].js',
  chunkFilename: '[name].[contenthash].js',
}

6. Troubleshooting

Common Issues

"Cannot find module 'webpack'"

  • Ensure webpack is installed locally: npm install --save-dev webpack webpack-cli
  • Use npx webpack instead of global webpack command

Memory Heap Out of Range

# Increase Node.js memory limit
export NODE_OPTIONS="--max-old-space-size=4096"
npm run build

Module not found errors

  • Check resolve.extensions in config includes your file types: ['.js', '.jsx', '.ts']
  • Verify case sensitivity in import paths (Linux servers are case-sensitive)

Cache corruption (builds not updating)

# Clear webpack's persistent cache
rm -rf node_modules/.cache/webpack
# Or disable caching temporarily
npx webpack --mode=production --no-cache

Loader configuration errors

  • Ensure loaders are installed: npm install --save-dev babel-loader css-loader style-loader
  • Check loader order (executes right-to-left): use: ['style-loader', 'css-loader']

Promise polyfill errors in older browsers Add to entry point:

import 'core-js/stable';
import 'regenerator-runtime/runtime';

Slow build times

  • Enable persistent caching (webpack 5+): cache: { type: 'filesystem' }
  • Use include/exclude in loader rules to limit file processing
  • Consider thread-loader or parallel-webpack for multi-core builds

Source maps not working in production

  • Ensure devtool: 'source-map' is set (not 'eval' in production)
  • Verify server serves .map files with correct MIME type

Debug Mode

Run with detailed logging:

npx webpack --stats=verbose
DEBUG=* npx webpack