Monday, July 24, 2017

How to Bundle a Simple Static Site Using Webpack

Webpack is all the rage right now. It has over 30,000 stars on GitHub and has been embraced by some of the big guns in the JavaScript world, such as the React and Angular.

However, you don't need to be working on a large-scale project to take advantage of Webpack. Webpack is primarily a bundler, and as such you can also use it to bundle just about any resource or asset you care to think of.

In this article, I'm going to show you how to install and configure Webpack, then use it to create a minified bundle for a simple static site with a handful of assets.

But Why Would You Want to Do That?

Good question. Glad you asked!

One of the primary reasons for doing this is to minimize the number of HTTP requests you make to the server. As the average web page grows, you'll likely include jQuery, a couple of fonts, a few plugins, as well as various style sheets and some JavaScript of your own. If you're making a network request for each of these assets, things soon add up and your page can become sluggish. If you include all of the above in one bundle however, that problem disappears.

Webpack also makes it easy to minify your code, further reducing its size, and it lets you write your assets in whatever flavor you desire. For example, in this article I will demonstrate how to have Webpack transpile ES6 to ES5. This means you can write JavaScript using the latest, most up-to-date syntax (although this might not be fully supported yet), then serve the browsers ES5 that will run almost everywhere.

And finally, it's a fun learning exercise. Whether or not you employ any of these techniques in your own projects is up to you, but by following along you'll get a firm understanding of what Webpack does, how it does it and whether it's a good fit for you.

Getting up and Running

The first thing you'll need is to have Node and npm installed on your computer. If you haven't got Node yet, you can either download it from the Node website, or you can download and install it with the aid of a version manager. Personally, I much prefer this second method, as it allows you to switch between multiple versions of Node and it negates a bunch of permissions errors, which might otherwise see you installing Node packages with admin rights.

We'll also need a skeleton project to work with. Here's one I made earlier. To get it running on your machine, you should clone the project from GitHub and install the dependencies.

git clone http://ift.tt/2vTrmMD
cd webpack-static-site-example
npm i

This will install Slick Slider and Lightbox2 — two plugins we'll be using on the site — to a node_modules folder in the root of the project.

After that you can open index.html in your browser and navigate the site. You should see something like this:

Our static site

If you need any help getting with any of the steps above, why not head over to our forums and post a question.

Introducing Webpack to the Project

The next thing we'll need to do is to install Webpack. We can do this with the following command:

npm i webpack --save-dev

This will install Webpack and add it as a devDependency to your package.json file:

"devDependencies": {
  "webpack": "^3.2.0"
}

Next we'll make a dist folder which will contain our bundled JavaScript.

mkdir dist

Now we can try and run Webpack from the command line to see if it is set up correctly.

./node_modules/webpack/bin/webpack.js ./src/js/main.js ./dist/bundle.js

What I am doing here is telling Webpack to bundle the contents of src/js/main.js into dist/bundle.js. If everything is installed correctly, you should see something like this output to the command line:

Hash: 1856e2c19ecd9b2d9026
Version: webpack 3.2.0
Time: 50ms
    Asset     Size  Chunks             Chunk Names
bundle.js  2.67 kB       0  [emitted]  main
   [0] ./src/js/main.js 192 bytes {0} [built]

And Webpack will create a bundle.js file in the dist folder. If you have a look at that file in your text editor of choice, you'll see a bunch of boilerplate and the contents of main.js at the bottom.

Automating Our Setup

Now if we had to type all of the above into the terminal every time we wanted to run Webpack, that'd be quite annoying. So let's create an npm script we can run instead.

In package.json, alter the scripts property to look like this:

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "build": "webpack ./src/js/main.js ./dist/bundle.js"
},

Notice how we can leave out the full path to the Webpack module, as when run from a script, npm will automatically look for the module in the node_modules folder. Now when you run npm run build, the same thing should happen as before. Cool, eh?

Create a Webpack Configuration File

Notice how we're passing the path of the file to bundle and the path of the output file as arguments to Webpack? Well, we should probably change that and specify these in a configuration file instead. This will make our life easier when we come to use loaders later on.

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

touch webpack.config.js

And add the following code.

module.exports = {
  entry: './src/js/main.js',
  output: {
    path: __dirname + '/dist',
    filename: 'bundle.js'
  }
}

And change the npm script to the following:

"scripts": {
  ...
  "build": "webpack"
},

In webpack.config.js we are specifying the entry point and output location of the bundle as properties of the configuration object, which we are then exporting . Run everything again and it should all work as before.

Continue reading %How to Bundle a Simple Static Site Using Webpack%


by James Hibbard via SitePoint

No comments:

Post a Comment