How to use Webpack — beginners’ guide
webpack is a bundling manager — one that has recently received quite a bit of attention! The reason is obvious: as web applications and websites get bigger and more complicated, managing their dependencies and bundles is critical. Even though webpack is mainly used for SPAs (single page applications), it doesn’t mean you can’t use webpack for designing a static website, too. In this article, I’ll show you how to streamline your design workflow using this cool tool.
Installing webpack
Before you can start using webpack in your project, you need to have Node.js installed first (download Node.js here).
Let’s create a folder for our application now:
mkdir webpack-sample && cd webpack-sample
Now, initialize npm:
npm init --yes
This action will initialize a simple npm package in your folder; this folder will now have a package.json
file with minimum content required.
Now you can install webpack; to use webpack in the command line, you need to install webpack-cli, too:
npm install --save-dev webpack webpack-cli
Using webpack
Let the fun begin! To tell webpack how to bundle your files, you need a config file with the default name of webpack.config.js
. You can choose another filename later, but for now, go ahead and create this file with the following content:
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
}
Let me explain what this very simple config file does:
- First, we define a constant named
path
withpath
module. We need it to tell webpack where to save our output file, which I’ll explain shortly. - Next, we export the module with an object that has two parts:
entry
(which tells webpack where the front door is, basically) andoutput
(which tells where to save the output bundle). - I chose to store my development files into the
src
folder and my built files into thedist
folder, but you can change them to fit your needs. - To tell webpack where to save the bundle files, you need to provide an absolute path, and that’s why we need the
path
module: thepath.resolve()
method resolves one path or a sequence of paths into an absolute path.__dirname
returns the folder name of the current module, which is our current folder.
You’re probably asking why the filename format provided above is a little strange. That’s because this formatting will tell webpack to automatically replace [name]
with the chunk name. You can provide a fixed name if you want, something like bundle.js
. But since you may have multiple entries, and you might also be chunking the bundle into multiple output files (this is one of the reasons developers use webpack anyway), it’s better to use this feature of webpack.
Adding the app.js file
Now we’re going to use a Lodash package on our webpage, and we’re going to install it through npm:
npm install --save-dev lodash
Lodash is a straightforward utility library that adds a lot of extra functions to JavaScript, making it much easier to use. All we need from Lodash here is to concatenate two words. You can use whatever packages you need for your website, but for now, this one is quite fine for demonstration. If you’d like to know more about this utility library, see Lodash documentation.
Now that our config file is ready, and we installed the lodash
package, we need to make our app.js
file so that webpack can process and bundle it for us. Let’s create a folder named src
and make a new file app.js
in it:
src/app.js
import _ from ‘lodash’;var h2 = document.createElement(‘h2’);
h2.innerHTML = _.join([‘Hello’, ‘World!’], ‘ ‘);
document.body.appendChild(h2);
Great! Next, to compile it, we just need to run webpack
, which you’ve already installed in the current directory (We’ll use npx
, a part of the Node.js package manager, to find the package in the node_modules folder and run it from there).
npx webpack
Now, if everything goes well, you’ll see that webpack will tell you which files it just processed and bundled for you, along with the size of each. Also, the new folder dist
is created with a main.js
file in it.
Congratulations! You’ve successfully used webpack to bundle your modules! All we have to do now is put that bundle on your webpage. Here’s how:
Consuming the bundle
To consume the bundle we just created, we will create a very simple HTML file in dist/index.html
with our script added into it.
dist/index.html
<!DOCTYPE html>
<html>
<head><title>Webpack Tutorial</title></head>
<body>
<h1>Webpack Tutorial</h1>
<script src=’main.js’></script>
</body>
</html>
Conclusion
We just created a bundle with webpack that included Lodash and our code. Bundling, if used with care, can significantly reduce the load time of a webpage. In our example, we could load a Lodash library with one script tag and our own code with another, thereby eliminating one request to the server with just a little effort… Imagine how useful this would be at a larger scale.
Maybe the most exciting part is that webpack allows much more functionality than what you just accomplished, and you can make a complete workflow that makes coding easier, including:
- Compiling SASS into css and even injecting css into the page during loading
- Use postcss to enhance css and make it more compatible with older browsers
- Use Babel to convert ES6 code to an older version of JavaScript for better compatibility
I hope this article has given you solid primer on webpack and I look forward to sharing more articles about this versatile tool.
Thanks for reading!