Published on

Getting Started with Webpack: Installation and Basic Configuration

Authors
  • avatar
    Name
    Hieu Cao
    Twitter

Prerequisites

Before starting, ensure you have the following installed:

  • Node.js: Download and install from nodejs.org.
  • npm (or yarn): Comes with Node.js for managing packages.

You should also have basic knowledge of JavaScript and the command line.


Step 1: Initialize Your Project

Create a new directory for your project:

mkdir webpack-demo && cd webpack-demo

Initialize a new package.json file:

npm init -y

This creates a default package.json file to manage dependencies.


Step 2: Install Webpack and Webpack CLI

To use Webpack, you need to install both Webpack and its command-line interface (CLI):

npm install webpack webpack-cli --save-dev
  • webpack: The core module bundler.
  • webpack-cli: Provides the command-line interface for Webpack.

Step 3: Create the Project Structure

Set up the following basic structure for your project:

webpack-demo/
├── src/
│   └── index.js
├── dist/
├── package.json
└── webpack.config.js
  • src/: Contains source files.
  • dist/: Holds bundled output files.
  • webpack.config.js: Configuration file for Webpack.

Create the src/index.js file:

console.log('Hello, Webpack!')

Step 4: Configure Webpack

Create a webpack.config.js file in the project root:

const path = require('path')

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  mode: 'development',
}
  • entry: The entry point for your application.
  • output: Defines the output filename and directory.
  • mode: Sets the mode to development for debugging or production for optimization.

Step 5: Build Your Project

Run the following command to bundle your files:

npx webpack

This generates a dist/bundle.js file, which contains the bundled JavaScript code.


Step 6: Add a Script to package.json

To simplify the build process, add a build script to your package.json file:

"scripts": {
  "build": "webpack"
}

Now, you can build your project by running:

npm run build

Step 7: Test Your Setup

Create an index.html file in the dist/ directory:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Webpack Demo</title>
  </head>
  <body>
    <script src="bundle.js"></script>
  </body>
</html>

Open dist/index.html in your browser to see the console message "Hello, Webpack!".


Conclusion

You've successfully installed and configured Webpack! This setup provides a solid foundation for managing and optimizing assets in your JavaScript project. Explore additional features like loaders and plugins to enhance your Webpack configuration.