webpack Tutorial: devServer & Hot Module Replacement (Live Reload)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
do you have any comments okay well hey welcome back to this bootcamp series in this video we're going to learn about something called webpack do you know what webpack is no now a lot of people are intimidated by webpack and so they avoid ever really understanding it now before we even jump into what webpack is i just want to say that technically you can get by with using it without ever understanding it so you can just copy and paste an existing configuration file for webpack and be up and running however i don't think that's a great idea i think it makes more sense to actually take a little bit of time to understand webpack i think this will give you a sense of calmness and confidence because in the modern web development world we're going to run into webpack again and again and again and being able to customize it or troubleshoot it or adjust it to fit our needs is a huge strength anyways without further ado let's jump into the action and get started with webpack okay so what exactly is webpack and why is it necessary well in our previous video when we were running node on our personal computer it was very easy to load or require in either community created packages or separate javascript files that we created as separate files just to stay organized the point is is that it was a piece of cake to pull in other separate files because node was running on our computer so obviously node had easy access to those files however what about client-side javascript where we want to deliver our javascript to visitors of a website that we build in that situation we can't just mention the name of a package from npm and expect it to magically be available to our visitors they don't have access to the node modules folder on our personal computer so this is where webpack comes into play webpack can bundle or pack together all of our different separate files and dependencies so that they're easy to deliver to the visitors of our websites now don't worry if me just explaining it in words doesn't make sense that's okay that's to be expected so from this point forward let's go ahead and get our hands dirty and actually start trying to use webpack so right now do this with me jump into vs code and i want you to open up or create a brand new empty folder so you can see on my desktop i have this new empty folder named learn webpack the name doesn't matter but with a new folder in vs code let's go ahead and create our package.json file if you have no idea what that is that's okay you can just go back and watch the very previous video here on my youtube channel but essentially if we open up our command line that's pointing towards our desired empty folder again you can press ctrl j or command j to toggle your command line let's just run npm init dash y so that will create our package.json file and now we can start installing packages so to start using webpack we just need to install two packages so run this command with me npm install the first package is just webpack and then a space the second package we want is called dash cli okay let's go ahead and push enter be patient to download those files it might take 30 40 seconds okay but once it does finish what do we want to do next well let's start actually writing or creating our javascript so within the root of the project folder that we have opened in vs code i need you to create a new folder so i'm just going to right click new folder or you can use this little icon up here but create a new folder with me and it needs to have this exact name it needs to be named src for source we need to give it this exact folder name because this is where webpack by default is going to look for our source code now don't worry a bit later on in this lesson we can learn how to tell webpack exactly wherever we want it to look we can configure webpack but for now let's just use the webpack default location so it's going to look inside src folder for a file named index.js so inside this folder say new file and name it index dot js again these locations are all customizable one hundred percent but we're just sticking with the webpack defaults for now okay now in this new empty file let's imagine we want to validate if a string of text is an email address or not now as we saw in our previous video we know that there's a package on npm called validator so imagine we want to use that in the command line we could just say npm install and the name of the package is validator okay so now with that installed in our new empty index.js file we can just say const validator equals require point towards the validator package okay and then on a new line of code let's actually use it so we can just say console.log and imagine we want to log out so validator dot it has a method of is email and just give it a string of text so this would return false or if you made it look like an actual email address this should return true so i'll just say this so this should be false let's go ahead and save this but now here's the interesting question and here's the entire point of webpack so imagine we want this to be client-side javascript that runs in the web browser of a visitor on our website so you and i on our personal computers we have access to the validator package from npm right we know it lives in our node modules folder but the visitors of our website don't have a node modules folder so we need some sort of way to bundle up or package up all of our dependencies or in other words we just need to tell webpack to do its job now this is super easy because we're using the default folder location of source or src and we named our file index.js literally all we need to do is go into the command line and say npx npx is a super useful command or tool to execute a certain package so remember in our previous video when we had our file of test.js and it was a bit of node code you and i were writing node and then the name of the file right well in this case we don't have any node code ourselves that we want to execute or run but we just want to use or run the webpack package so if we say npx and then you can give it a package name if you don't already have it installed it will try to download it from the internet from npm in our case we already installed webpack so this should be lightning fast we just say npx web pack and that's it let's press enter now don't worry for now we can absolutely ignore this warning message however notice that that created a brand new folder named dist and inside it it created a file named main.js this is our bundled up file that webpack generated for us and no matter how many different separate files we used in our code or how many different packages from npm we import webpack bundles it all together in this one convenient file that we can have our visitors download so if we want to really test this out let's maybe create an html file really quick and load it now in the real world you wouldn't create a source html file in your dist folder but for now this is perfectly fine just right click on the disk folder and let's say new file let's call it index.html inside this file we can just hit dock and then hit tab for a skeleton and then right before the closing body tag let's say script and then hit tab give the opening tag a source and just point towards main.js right that file that webpack automatically created for us above that maybe we want a heading level one that says hello and welcome and then maybe below that we want a paragraph with a little bit of lorem ipsum okay let's save this and now let's open this file in our web browser so i'm just going to drag and drop that index.html file in my dist folder i'm just going to drag it on top of chrome okay there we see the basic html but what we really want to see is the console remember in our file we were logging to the console whether this email address or whether this string of text is a valid email or not so if i check the console in my browser cool we see false however if we change this to john at test.com and hit save that should be a valid email address now so we would expect to see true we do need to bundle up our code again so in the command line just run npx to execute a package so npx webpack hit enter that's going to rebundle up should only take a couple of seconds back in the browser if we refresh perfect we see true now before we move on and learn more about webpack i do want to go off on a tiny bit of a tangent and that is that you saw me just use this require syntax to load in this validator package i used this because we're already familiar with using require from our previous video when we were writing node code so this is the default or traditional way to import a package in node however in the latest versions of javascript itself or ecmascript there is now a native way to import a package or a file or a module so i do want to show you the more modern syntax as of today this would not work in the node environment out of the box without a bit of configuration but it absolutely will work in this newest version of webpack so we can just say import validator from and then a string of text and just the package name so if we hit save and then we can package it up again so npx webpack refresh in the browser and it still works perfect really quick why don't we practice creating our own separate file uh maybe a function called the double mirror triple me and practice importing that so for example let's also log to the console um triple me and give it a value of 10. so we would expect this to return a value of 30. now at the moment we don't have this function so let's actually go create a triple me function in an entirely separate file so within our source folder let's say new file let's name it tripleme.js inside this file let's just say function triple me parentheses curly brackets let's have one parameter to receive the incoming number and then just return that asterisk or multiply three at the very bottom of this file in our previous video when you're using the require syntax to import and export we would have said module dot exports equals triple me however if we're using the javascript or ecmascript native way of importing and exporting instead we would say export default whatever you want to export so in this case triple me so we can save that now back in our main file before we use it right here let's import it up at the top so you just say import triple me from a path right so quotes dot slash to look in the current folder triple me let's go ahead and save that and now tell webpack to bundle up our code again so in the command line npx webpack give that a couple of seconds refresh in the browser perfect we see 30. now if you're anything like me at this point you're probably sick and tired of having to manually run npx webpack every time we want to rebundle our changes well to get around that in the command line we can instead just say npx webpack and then a space dash dash so two dashes watch okay with the watch option like this now if we press enter not only does that run a task but it never actually finishes that task is still running and it's just watching and waiting so if i change the triple me number to 20 and hit save back in the browser if i refresh you can see it's already 60. so now you can change this as many times as you want webpack is just running in the background continuously watching our code for changes anytime it detects a saved change it's going to rebundle okay now changing gears to a new topic when we're writing client-side javascript like this we do want to pay attention to the file size of our bundled file so for example in the dist folder if you right click on the main.js file that webpack is creating for us and then you can either click properties or get info you can see that it's already kilobytes and we really haven't done anything yet this is because we imported the entirety of the validator package from npm now whenever you import a package that you're going to force the visitors of your website to download you do want to be mindful of the file size so a better approach if we know that we're only going to use this one feature of is email right that one method from the validator package instead we can say import validator slash lib slash is email from the individual npm documentation page for a package it will usually spell out the exact text that you would use here to import just one method but now maybe let's change the variable name here to is email and then that's what we would use down here so get rid of the validator dot and just directly use is email here so if we save that webpack is still watching us it's going to rebundle up and now you can see instead of 74 kilobytes our bundled up file that the visitors of our website have to download now it's only eight kilobytes now right now when we're just getting started with webpack i don't want you to obsess on the file size you can worry about that down the road but this is something that i want to be on your radar okay at this point let's jump back to actually learning about webpack itself so now that we've used the default folder location of src and the default file name of index.js you're probably wondering what if we don't want to use those folders and file names what if we want to use our own custom values well you absolutely can we can configure webpack however we want so to stop the current watch task in the command line you can just press ctrl c right that way webpack doesn't just sit there and watch us endlessly okay and let's learn how to start configuring webpack so in the root of our project folder we just want to create a new file and it needs to have this exact name webpack.config.js okay now in this new empty file we say module.exports equals curly brackets right an object and now inside this object we give webpack different properties and values and we can tell it to do whatever we want it to do so for example imagine instead of our source code living in this folder named src what if we wanted this folder to be able to be named app or anything else for that matter but just so you and i are on the same page why don't we rename our source folder to just app app okay and then also imagine what if instead of our main file being named index.js what if we wanted it to be named maybe just app.js so for example let's rename it you could name it anything right but just so we're on the same page let's call it app.js okay so now in this configuration file we would just say entry we give it a property of entry quotes dot slash for the current folder then we would look inside the app folder and then we want the file named app.js so we're just telling webpack this is the entry into our application or this is the beginning of what we want you to start parsing and bundling up the dependencies for okay next what if we wanted to control where the bundled file gets output now i actually like the folder name of dist but you could use a different folder name if you wanted to but let's try customizing the name of the generated file so let's actually delete main.js and imagine instead we want webpack to generate a file named mybundle so in this object let's just add a comma at the end of this line let's have another property named output colon this is actually an object itself with multiple properties so we give it one property of file name colon and let's call it quotes mybundle.js you could name it anything you want that's just what i'm choosing as an example comma another property of path so now this is where you could point towards any custom output folder i'm just going to stick with the dist folder though now webpack actually needs an absolute path to the folder here so instead of just spelling out a directory like this we do need to do something a little bit different for the output path here so up at the very top of our file let's import a core part of node called path so we can just say const path equals require in path so remember in our previous video when we required in the fs module that was just a built-in part of node itself well path is also a built-in part of node so now down here for this path property we can just say path and then call a method it has named resolve let's say underscore underscore so two of them and then der name so that will give us the current folder that we're in right now at the moment and then comma and then we can just spell out whatever actual folder name you want to output to so i'm going to stick with dist but you could change this okay but let's go ahead and save this configuration file and test it out so remember we changed our source folder to be named app we changed the name of our main file to app.js and now our dist folder we are hoping to see a new file named mybundle init so in the command line just run npx webpack push enter cool in dist i now see mybundle.js we can test it out to make sure it's working back in our html file just change what file name we're looking for here so instead of main.js it would be my bundle give that a save back in the browser refresh cool it's still working perfectly also if we don't want to have to remember to include dash dash watch in order to have webpack watch us ongoing instead in our config file maybe right after this output we can just say comma and have another property watch and just set it to true so now if we run down in the command line npx webpack well just like before now it's just going to continue running until we tell it to stop so if i change this to 500 hit save back in the browser reload it's going to automatically rebundle after every saved change now that watch ability is great it's very convenient but wouldn't it be even more convenient if webpack could reload the browser for us right if we didn't need to manually hit command r or f5 to reload our browser well not only can webpack do that and refresh the browser for us it can go one step further instead of even needing to reload the browser it can just inject or replace the newest version of our javascript into the browser in memory without even reloading now in order to make any of the things i just described possible we do need to install something called webpack dev server now this is going to be the final topic in this video and i do want to point out that this is entirely optional you do not need to use the dev server however it can speed up development and it is pretty luxurious to just have your newest code always in the browser without even reloading at all anyways let me show you how we can set this up so in the command line let's press ctrl c to tell webpack to stop watching us okay and the package we need to install so npm install the name of the package is webpack dash dev dash server okay go ahead and press enter okay now let me show you how we use this so back in our config file let's get rid of the watch true that's no longer necessary if we're going to have a dev server so just a new property in our config object and call it it needs to be named dev server uppercase s colon this receives an object itself inside that object we give it a few different properties so first of all let's tell it which port on our computer to run on support let's try 8080. if this doesn't work you could try a value of 3000 or 4000 but let's go with 8080. i'll show you where this number comes into play in just a moment comma and then let's also tell it which folder to use as the base for our dev server preview so why don't we just use our dist folder right that's what contains our web page our index.html and that's what contains our bundled file so we give it a property of content base colon and then let's use path resolve again to give it an absolute path so path dot resolve underscore underscore name comma dist okay and then on a slightly unrelated note to stop seeing that warning message in the console about being in production mode we can just add a comma and say mode development so if instead we set this to production that's for the live version of our website not us while we're developing for our own convenience so production is going to minify the file and use short variable names remove all white space basically make the bundled file be as small as possible so it's quick to download however compressing it like that does probably add a few 100 milliseconds or longer and also removes potentially really valuable debugging information for us while we're developing the site so when we're not ready to actually deliver our files to the public yet let's set this to development right this way it's optimized for us while we're developing the site so let's go ahead and save this and now this might seem confusing at first but i actually want you to delete the bundled file in our dist folder so i'm going to delete mybundle.js the reason i'm doing this is because webpack dev server by default doesn't actually output the bundled file to your hard drive instead it just makes this file name available in memory this allows it to be even faster in between bundles every time we save it can just store the contents of the file in memory which is always going to be way faster than actually saving to a hard drive so with this file saved let's test it out in the command line we just run npx web pack dash dev dash server go ahead and press enter okay now this is why they call it webpack dev server instead of visiting the local html file on our hard drive we actually want to visit a different address so up in the address bar i want you to visit localhost colon 8080 right because that's the port number we chose cool now you can see the website looks exactly the same and if we view the console we see those same values true and the triple me value however check this out if we make a change to our main javascript file right if i change this number to 1000 and hit save notice back in the browser i don't even need to hit refresh or reload webpack just automatically reloads for me also if we look in our dist folder we don't actually see that file named mybundle.js however up in the address bar if you visit localhost colon8080 slash mybundle.js you can see it that file absolutely exists in memory and is available from this url but webpack isn't writing it to the hard drive and this allows webpack to be even faster so this is perfect when we're developing our site and we're going to be saving changes hundreds of times and testing and debugging in the browser and then when it comes time to actually generate that bundled file well you can just tell this command to stop watching us tell the dev server to stop running i should say so press control c and then when you actually want to bundle your files so that a file does actually live on our hard drive in the disk folder you could just run npx webpack instead of webpack dev server so when i run that cool that actually does save the file to the hard drive but we don't need that for right now so i'm going to delete that okay now before we bring this lesson to a close i want to show you a super power that webpack has so at the moment if i start up that dev server again npx webpack dev server yes it will reload the browser for me every time i save a change so if i put this to 2000 hit save it is going to reload the browser for me so in the console i see 6000 if i change this to 5000 in the console we see 15 000 you get the idea however it's still reloading and refreshing the browser right you can prove this by if i select or highlight content on the page and then just make any change here so if i put this to a value of two hit save notice it refreshed the entire browser and it lost my selection of text now there's nothing horribly wrong about that but we can make this even faster if we adjust it so that instead of having to reload the browser just gets injected on the fly with the newest copy of our javascript this will give us the fastest possible performance and experience while developing so to set this up let's go ahead and hit ctrl c in the command line to tell the current task to stop running and in our config file within dev server we just need to give it another property in addition to port and content base so let me add a comma here and just say hot colon and set it to true let's go ahead and save that file so this is going to enable something called hot module replacement in webpack so with this in place we're just one step away from having the blazing fast performance now in our main javascript file right the file that is the entry point into our app so for us that's this app.js file at the very bottom just type this out with me if so just an if statement the condition is if module dot hot curly brackets what do we want to do if that's true basically meaning what do we want to do if the hot feature is running and this is a dev server not the live version of our website if it's true then just say module.hot call a method of accept essentially if this feature is enabled then accept the newest updates of the file so let's save this and test it out it's pretty cool so in the command line we can just run npx webpack dev server okay now check this out so you might need to refresh just the initial first time on localhost 8080 but now after that we don't need to ever refresh again so if we check the console we see those values of true and six and if we go back into app.js and change this number to 10 hit save yes in the console if we scroll down we do see that got tripled to 30 but now to really prove that it's not even reloading the browser and it's just always injecting the code into memory check this out if you just select a bit of text on the page now obviously if you manually hit refresh you lose your selection right so this is how we can test that the browser is not even reloading if you just select that and change this to just a different value hit save notice that didn't even unselect my selection but if you check the console we do see the latest value this may not seem like a big deal but when you start doing more advanced things in the browser it can be really nice not only from a speed and performance standpoint but also you don't lose any of the values in the browser's memory you don't lose the current state of the web page it can just be very handy to inject the latest code without a reload so really quick just to test this out again now if we select this paragraph maybe we could write a little bit of javascript that changes the value of this headline so back in app.js just as a quick test i'll even move this window down so we can see the browser in the background but if i say document.query selector and just select the heading level one and say inner text should equal hello if i hit save notice in the background that got updated in real time and the browser didn't even reload we didn't even lose the selection of this text so you can see how for development and debugging this is just incredibly fast now don't worry that was the last real feature i wanted to show you in this video but before we bring this video to a close i do want to show you perhaps a more elegant way of calling our commands so there's nothing wrong if i press control c to stop that current task there's nothing wrong with using npx and then either webpack dev server or just webpack however maybe you don't want to have to remember that name of webpack dev server maybe you don't even want to have to remember the name of webpack instead maybe it would be nice if we could just say npm run dev whenever we wanted the dev server to start and maybe we could just say npm run build whenever we wanted the regular webpack task to run that actually saves the file to the hard drive so really quick at the end here this doesn't have anything to do with webpack this just has something to do with npm itself i want to show you how we can create our own npm scripts so that we can run commands like this so to do this we're just going to jump into our package.json file okay in this file this is the same file that keeps a list of our dependencies but there's also a property named scripts by default there's just this one named test but right above test so within the scripts object let's say quotes and now we can make up any name for our command we could call it pizza or unicorn or anything but why don't we call one of ours dev so colon and then quotes after the quotes be sure to include a comma here and now this is just the actual command that we would have typed in the command line so let's just say webpack dash dev server okay then let's have another task named build so on a new line here quotes build colon quotes be sure to include the comma here in the quotes just say webpack so now whenever we want to run this task we don't need to remember webpack dev server we can literally just say npm run dev and then when we want to actually build our file and save it out to the hard drive we don't need to remember webpack even though that's not that hard to remember we can just say npm run build so be sure to save this file and then one quick note back in our config file i'm actually going to get rid of this mode line completely and i'll get rid of this trailing comma here too save that this way when we run our dev server command the mode can default to development and when we run our build task it can default to production don't worry in a future lesson i'll show you how to use conditional values depending on the current task that's running but for now this should work fairly nicely so to test it out in the command line now if we want to start up our dev server we can just say npm run and then the name of the script that we created in our package.json file so we call the dev so just npm run dev hit enter cool so i can still refresh and visit localhost 8080 perfect let me stop that task okay and then remember i deleted the actual bundle file that lived in my hard drive and dist so let's test that out actually generating it we can just say npm run build push enter and because that's using webpack instead of webpack dev server it knows to actually generate it onto the hard drive so now we see it mybundle.js and you're free to use that anywhere you would normally use a javascript file for the general public to download cool and that is going to bring the technical aspect of this video to a close congrats on making it to the end of this video now let's talk about where we go from here so let's actually get back to the task at hand remember a lesson or two ago we were working with react and we needed a way to automatically transpile our jsx into traditional javascript well now that we understand what webpack is what webpack can do for us and the basics of getting up and running it's going to be a piece of cake to get it to transpile our jsx for us and as you might have guessed that's exactly what we're finally going to set up in our next video if you're enjoying this boot camp series so far as always i'd appreciate it if you shared the link with your friends and family take care and i'll see you in the next one [Music]
Info
Channel: LearnWebCode
Views: 20,295
Rating: 4.9467311 out of 5
Keywords:
Id: yR25JoybTxo
Channel Id: undefined
Length: 37min 7sec (2227 seconds)
Published: Mon Sep 28 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.