This article was originally published at https://www.blog.duomly.com/what-is-webpack-and-how-to-setup-webpack/
Intro to Webpack tutorial
Webpack is a tool very often used in software development, and it’s pretty useful. For many junior and even mid developers, Webpak can be the darkest nightmare, and it was scary for me as well. By all the power, I tried to avoid setting Webpack by using tools like create-react-app
to build a new ReactJS application and never have to do any changes inside the ready config, as it seemed confusing.
But for every developer, it comes the day when you just have to beat the beast and learn how it works, to set Webpack in a more efficient way for a particular project and make your software even better.
In this article, I’d like to help you with this overwhelming and confusing area of development and explain some basics about Webpack, what it is, why we use it, how it works, and the most important, how to setup Webpack.
For those of you who would like to watch instead of reading, as always, I have a video tutorial on our Youtube channel.
Let’s start!
What is webpack
Webpack is a module bundler for web applications that bundles, minify, and transpile JavaScript code to the code understandable by all the browsers. As a Javascript developer, you probably have heard about modules before. Webpack has a broad definition of what modules are, and it takes into consideration: ES modules, CommonJS modules, CSS imports, image URLs, or AMD modules.
It’s important to understand that Webpack is not used on the actual page in the production environment. It’s running during the development process. What we can see life is a code generated as a bundle by the Webpack.
How Webpack works?
Webpack goes through your application and creates a dependency graph consisting of modules that the application needs to work properly. Next, based on the dependency graph, it creates a new package, mostly it's just one file called bundle.js
, but it can also be divided into chunks, so smaller files are loaded as necessary. The package file created by Webpack is imported as a script in the HTML file of the application and makes the app working as expected.
Although since version 4.0, it’s not required to create a config file to use Webpack to bundle your project, it's good to know what’s inside to adjust the config and get more profit from using the tools.
To be able to create a well-working config, it’s important to understand the core concepts of Webpack:
Webpack entry point indicates where Webpack should start building the dependency graph. From this point, it will find the other dependencies required to provide the proper functionality of the application. By default, it’s ./src/index.js
Webpack output is a point where the Webpack emits bundles and the name of the bundle file. By default, it’s main.js
, and the folder is ./dist/
, but inside the configuration file, you can place it somewhere else in the application and name the file differently.
Webpack loaders are used to process any other types of files, as Webpack by default, can recognize only JSON and Javascript. That’s why we need some additional settings for images or styles. The principal task of the loaders is to convert those sources to valid modules, which can be added to the dependency graph. There are two properties in high-level Webpack loaders configuration, test
to identify which files and folders should be transformed, and use
to indicate which loaders should be used for transforming.
Webpack plugins are used to perform a wider range of tasks, like bundle optimization or environment variables injection. To use plugins, we need to import them using require()
, and then add it to the plugins array.
Webpack mode is a parameter that lets Webpack know what’s the environment of the application. It can have the following values: development
, production
or none
. By default, the mode is set to production
.
Well, when you understand most of the important Webpack concepts, we can jump to a practical Webpack setup.
How to setup Webpack?
At this point, I’d like to go through setting the simple Javascript application with Webpack and set by step show you how it works. For the purpose of this tutorial, I’ll be using Webpack 5.
Webpack install
Let’s start by creating a new project and initialize npm.
mkdir webpackTutorial && cd webpackTutorial
npm init -y
Next, let’s install all the necessary tools: webpack
and webpack-cli
.
npm install webpack webpack-cli
When this step is finished successfully, let’s create a simple project structure and a file with some dummy code.
So, let’s open the project folder, and let’s add the src folder and index.js file like below.
Inside the index.js
file, let’s add a simple Javascript code to use to build our bundle and be injected into our main page.
const title = document.createElement('h3');
title.textContent = 'Webpack made easy!';
const page = document.querySelector('body');
page.append(title);
Webpack config
To start with the Webpack setup, we need one more file. Inside the root folder, let’s create the file webpack.config.js
, and let’s start by setting the entry point and output for our application bundle.
const path = require('path')
module.exports = {
entry: {
index: path.resolve(__dirname, './src/index.js')
}
}
In the first line of the code, we imported the path module, which provides utilities for working with paths of files and directories. It’s a part of Node.js.
Then, we told Webpack where to look for the first file, which will be the base to create a dependency graph.
Next, we can setup the folder and file where we would like Webpack to save our bundle, and we will set it as an output
.
const path = require('path')
module.exports = {
entry: {
index: path.resolve(__dirname, './src/index.js')
},
output: {
path: path.resolve(__dirname, './build'),
filename: '[name].bunde.js'
}
}
In the output part of our Webpack config, I set the location of the bundle to ./build
folder instead of default ./dist
, and as a filename, I passed a variable, so the [name] of our bundle file will be as defined in the entry index.bundle.js
.
Right now, we can try out our Webpack bundle, as we have a minimum config ready. Let’s open package.json
file, and let’s adjust it to run Webpack from the console.
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
When it’s ready, open the project in the console and run the following command.
npm run build
When it’s done, you should see something like the image below in your console. Also, you’ll be able to see a new folder in your application with the bundle file. Nothing interesting happened there yet, but the build exists.
Webpack - Html Plugin
Right now, I’ll show you how to add plugins to your Webpack config to make it more flexible. We want to add some HTML to our application, so we need it to be generated, and for this, we need a Webpack plugin. Let’s install html-webpack-plugin
.
npm install html-webpack-plugin
When that’s installed, we can go back to our config file and configure the plugin.
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
...
plugins: [
new HTMLWebpackPlugin({
template: path.resolve(__dirname, "./src/template.html")
})
]
}
Before we move forward to update our build, we need actually to create our template.html
file.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello world!</title>
</head>
<body>
Hello world!
</body>
</html>
Now, let’s build the bundle again and run the index.html
file you will find in the build
folder in the browser. You should be able to see the content of the HTML file we’ve created and the text we used in our index.js
file.
Webpack loaders
If we would like to add any other type of files like assets or CSS, we need to add loaders that allow Webpack to understand them, compile and use them. Let’s add some images to our code, and then we will need to set the assets loader.
Let’s create a new folder inside ./src
, and let’s call it assets. Let’s add any image there. And next, try to import it in your index.js
file, and let’s append it to our page.
import koala from './assets/koala.png'
...
const img = new Image();
img.src = koala;
page.appendChild(img);
Right now, to be able to update the bundle, you need to add a loader in your Webpack config.
module: {
rules: [
{
test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
type: 'asset/resource',
},
],
}
Let’s run the build once again, and let’s refresh the index.js
file in the browser, and then you can see your image below the text.
Now, let’s learn how to use styles with Webpack.
Webpack CSS loader
Let’s create a simple styles file, and let’s import it into our index.js
file.
// style.css
body {
text-align: center;
margin: 20px;
}
h3 {
color: #333333;
background: #f5f5f5;
padding: 20px;
}
img {
max-height: 500px;
}
//index.js
import './style.css';
Now, to be able to see the changes, we need to install loaders for CSS: style-loader
and css-loader
.
npm install css-loader style-loader
When those are installed, let’s go back to our Webpack config, and let’s add the loader rule.
module: {
rules: [
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
},
{
test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
type: 'asset/resource',
},
],
}
After that, we can rerun the bundle and see if our styles work.
It seems like it works!
Conclusion
Congratulations, you’ve just created a simple Webpack setup!
In this article, we went through what is Webpack and how Webpack works. Next, we went through the most important concepts of Webpack that you need to understand to build any Webpack configuration.
I hope this knowledge will help you next time when someone will start talking about Webpack. You can be as confident as never before and stop being scared of the big Webpack monster.
In my opinion, it’s not so difficult and confusing when you will know what’s the purpose of using it, how it works, and what the concepts are responsible for.
Thank you for reading,
Anna from Duomly