Do you remember in jQuery how when you wanted to add additional functionality than was provided, you would have to load in library after library in order to get what you wanted?
After a while, it probably became very cumbersome to manage didn’t it?
It probably ended up looking something like this:
[image of too many script source tags loaded in]
You would have to add in a bunch of different script tags, load them into the relevant documents, and then on top of that, make sure that they weren’t conflicting with each other. Which they unfortunately, usually were. And then when they were, you were given highly obscure error messages at best in order to deal with them.
In VueJS, while you are able to do things in the jQuery multiple script src tag way, there is an alternative that is also available.
That alternative works from the command line.
That alternative is Webpack.
What Is Webpack In VueJS?
While Webpack is infact available to any JavaScript based project, we are only, for the purposes of this tutorial, going to focus on it as it pertains to VueJS.
Before we get into what Webpack is, we first must understand why it exists in the first place. We will know that by understanding the problem that Webpack solves.
The Multiple Scripts Problem & How Webpack solves this
What Webpack fundamentallly does is make your VueJS (along with a variety of other frameworks) development process easier.
Before we get into how it does this. Let’s first take a step back and understand why Webpack exists in the first place.
As the web evolved, two fundamental problems began to emerge for developers.
- Too many libraries. To meet the UI demands of the modern web (link to post that explains why here), more and more external libraries and plugins were needed within projects. This got to a point where you could be needing more than 100 external libraries for your project at any given time. Sometimes many more. Imagine 100+ script src additions within your html file. This would be unmanageable.
- Speed increasingly becoming important. To respond to the increasing demand for performant, responsive, desktop-app like UI’s that was now necessary for the modern web, many developers DID opt to go for simply adding in a bunch of libraries directly. This, as you can imagine, lead to increasingly slower and slower UI’s and load times. This also lead to a dramatic decrease in the user experience. I think you can probably remember this time period. It was around 2011/2012 when jQuery was just reaching its peak. In response, many services such as Google, responded by imposing penalties for sites that were deemed to be too slow for the user, so that the fastest sites ultimately rose to the top. The consensus gradually became that the web and its websites just had to get faster, no matter how many libraries needed to be loaded. The web needed to become more efficient. Knowing how the economics of the web work, especially when Google institutes a penalty, the result of this became that web developers now made speed a priority.
To respond to all of these increasing concerns a solution, ideally, a simple one, was needed.
In came Webpack.
How Webpack solves the multiple scripts problem
Instead of having to load in multiple libraries and manage them in an obscure way, with Webpack, you could now simply load in and manage your libraries within your command line. Using what is known as a ‘build’ script. These libraries would be loaded and stored within discreet folders in your project library and then made easy for use and loading when necessary.
Webpack would also make it easy for you to compile your newly loaded web libraries, so as to make the speed at which these libraries load much better. As well as this, Webpack would allow you to use new JavaScript functionality (such as ‘require() for modules’) within your code that was not readily available in modern browsers.
It could do this because you could write the code you wanted in your pre-compiled, or ‘built’ scripts, and then once you were ready, you could ‘build’ and compile them down into a format that the modern browsers could read and understand. Thereby unlocking a massive amount of new functionality.
While Webpack fundamentally is a JavaScript library bundler, it also allows for more useful functionality to occur during that bundling process.
Functionality such as:
- Linting. Which is the analysis of your code for any potential errors.
- Custom Loaders. Because Webpack by itself only understands and compiles JavaScript, custom loaders can be introduced to it in order to allow for the understanding and compilation of more types of resources such as CSS and images.
- Plugins. Which allow for custom tasks to be run on your scripts at compilation time, such as the injection of custom data (ie. environment variables) and/or the custom optimization of your compiling bundle.
All of the above can be summarized as part of the hook functionality that Webpack provides. This basically creates a way to ‘hook’ into the bundling/build process as it is going on and manipulate your scripts in various different ways, with various processes, such as the ones listed above.
How To Use Webpack (Within A VueJS Project)
How Webpack works within a VueJS project
Just like the starting point of any Vue app is in the initial Vue instance. Likewise, the starting point of any Webpack build is in what is known as the ‘entry file’. This is simply the file that is specified within the webpack.js.config file as the place that Webpack should read to find and then bundle our imported modules.
In the case of a Vue project, this entry file is usually the ‘{}.js’ file. We will jump into this in the demo project in a minute, but before we do that, let’s get a reminder of what loading in libraries (modules) is like without Webpack.
Vue without Webpack
Vue without Webpack or any other bundler, looks a lot like jQuery in terms of folder and file organization.
You simply have a lot of libraries being loaded into the pages that need them, one by one. Usually within your header section in your HTML page. Like this:
<!DOCTYPE html>
<html>
<body>
<h1>Your Non-Webpack VueJS Project</h1>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js">
</script>
</body>
</html>
Here you can see that we are directly loading in our standard VueJS script and then below that we are loading in our Axios library. Which is a popular library that simply allows us to run HTTP requests.
Note: In Vue as well as in other well known JS frameworks, what we normally used to call libraries are now commonly referred to as ‘modules’. This is largely due to the influence of Node.JS and the way in which these libraries are presented within the code.
They are typically loaded in, as we will see below, in the way that ‘modules’ in other languages and frameworks, such as Python do.
We may use our loaded in Axios library above, like this:
<div id="app">
{{ info }}
</div>
new Vue({
el: '#app',
data () {
return {
info: null
}
},
mounted () {
axios
.get('https://api.coindesk.com/v1/bpi/currentprice.json')
.then(response => (this.info = response))
}
})
You will note here that the above seems pretty straightforward. But remember that we are only loading in one library. In most projects that are required to meet today’s modern level of complexity, as much as 20-100 different libraries could be needed. Sometimes much more.
Since we need them all. The best thing to do to make them manageable is to simply bundle them up and automate this process so that we are not having to deal with each one, one by one. This is what we do with Webpack.
Vue with Webpack
Using Webpack changes the way that you both write your code, as well as the way in which you organize your folder structure.
While in our previous ‘without Webpack’ example, we could get away with putting everything in one page, and simply loading in our libraries from a CDN. Doing this massively limits the potential of our application and what we can ultimately do as developers.
This style of organization, both in terms of code and overall project structure is simply too primitive to deal with the demands that modern website building entails.
The Modern web project code and folder structure, and how it all works (In Vuejs)
The folder structure
The easiest way to get started with Webpack within your Vue project is by using the ‘Vue CLI’. Check out the link to learn more about that if you don’t know already. We will skip the installation and jump right in.
This is the typical folder structure that we get from a full Vue project, installed using the Vue CLI.
[image here]
Within this structure, our Webpack basically coordinates everything that we’ve described above from within our webpack.config.js file. This is our command center. It is here that we set our ‘hooks’ such as our loaders (in this case we have our Vue loader set within it), as well as all of the other necessary plugins we need.
Loading in and managing libraries (modules) with Webpack within this structure is as easy as running ‘npm install {package you want}’ while within our newly installed Vue folder directory, in the command line.
In this case, we will load in Axios.
Navigate to your VueJS folder directory and type in ‘npm install vue-axios’.
This loads in and places our Axios library within the ‘node_modules’ folder within our directory.
The File Structure
Once we have done that, we will simply add in our imports of Axios in our Vue ‘entry file‘ {name of the file}, like this:
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
What this basically does is place a reference for Webpack to know (as it has already been specified within our webpack.js.config) that we will be reading this file for modules that need to be loading in and bundled at compile time.
All of our loaded modules in the future will be referenced within this entry file.
There is no need to load in anything else after that. When we have written the code we need. We will simply compile with our Webpack enabled command, in this case, ‘npm run dev’ and it will handle everything else that is necessary to get it to work with our code.
Let’s now use our newly loaded library in an example to demonstrate what we mean here.
Let’s open up our App.vue file. We will be making a call to an API and then displaying our data to our root <div>.
[example code of the App.vue file]
Notice that the only things we have in this page is the code we need. All of the other parts of the code, such as the header, footer and other libraries are going to be bundled in once we run our Webpack script.
When we’re ready to view this code, we will simply run this script. Like so, within our command line, inside of the project folder: ‘npm run dev’.
This will bundle up our code, from its present and then push it to the dist folder as browser recognizable JS, CSS and images.
As you can see here. Webpack is not only allowing us to load in our libraries in a very easy way but it also, with the additional functionality it adds via its ‘hooks’, the loaders and plugins, allows us to unlock amazing functionality at a higher level in our projects, such as the ability to use custom ‘App.vue’ files and structure our projects in the way that this makes possible. Via the Webpack ‘Vue Loader’ in this case.
Webpack ultimately is a key component of the modern web. With the ever-increasing complexity that most developers have to now deal with and the endless array of tools that need to be managed, making the process of bringing them together and working seamlessly, as well as adding more useful, efficiency generating functionality on top of that, only make it greater.
With Webpack, your workflow, especially in VueJS, which is already making things easy, makes it just that little bit easier.
To be the first to know when we publish a new post or book, you may also subscribe to our email list below