In this post, we will walk through the process of setting up and configuring Webpack for a simple web project. Webpack is a popular module bundler used in modern web development to bundle and optimize web assets like JavaScript, CSS, and images.
Before we get started, we need to install Webpack globally on our machine. Open your terminal and run the following command:
npm install -g webpack webpack-cli
This will install the latest version of Webpack and the Webpack command-line interface (CLI).
Next, let's create a new directory for our project and navigate into it in the terminal:
mkdir my-webpack-project
cd my-webpack-project
We will use NPM (Node Package Manager) to manage our project dependencies. Initialize a new NPM project by running the following command and following the prompts:
npm init
Now, let's install Webpack as a development dependency of our project. Run the following command to install Webpack locally:
npm install webpack webpack-cli --save-dev
This will add Webpack to your project's devDependencies
in the package.json
file.
Webpack uses a configuration file to define how it should bundle your project's assets. Create a file named webpack.config.js
in the root of your project directory and open it in your preferred code editor.
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
};
In this basic configuration, we specify the entry point of our application (index.js
in the src
directory) and the output path and filename for the bundled JavaScript (bundle.js
in the dist
directory).
Now, let's create a simple JavaScript file to serve as the entry point of our application. Create a file named index.js
inside the src
directory and add some code:
console.log('Hello, Webpack!');
We are now ready to bundle our assets using Webpack. Open your terminal and run the following command:
webpack --mode development
This will tell Webpack to bundle your assets in development mode. After the bundling process is completed, you should see a bundle.js
file inside the dist
directory.
Finally, let's test if our bundle is working correctly. Create an HTML file named index.html
in the root of your project directory and add the following code:
<!DOCTYPE html>
<html>
<head>
<title>Webpack Demo</title>
</head>
<body>
<script src="./dist/bundle.js"></script>
</body>
</html>
Open the index.html
file in your web browser and check the console. You should see the message Hello, Webpack!
logged in the console, indicating that our bundle is working correctly.
Congratulations! You have successfully set up and configured Webpack for a basic web project. In the next post, we will explore how to manage different types of assets with Webpack.