Learn Dynamic Module Imports In 11 Minutes

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
if you want to write faster more performant code then dynamic module imports are what you need and in this video i'm going to show you exactly what they are and give you three real world use cases of where i would use dynamic module imports [Music] welcome back to web dev simplified my name is kyle and my job is to simplify the web for you so you can start building your dream project sooner so that sounds interesting make sure you subscribe to the channel for more videos just like this now to get started i just have some really basic code setup where i have this user file which just has a class for a user which takes a first name and a last name it has a print user function that exports which just prints out the first and last name and then in our script we're using a standard import to import the user the print user function we're creating a new user and then we're printing out that user and as you can see on the right side of our screen we're getting the result super straightforward stuff this is what you would use almost always when you're dealing with import and export statements now the way this code currently works is that it's going to first download our script.js file and then immediately it's going to download this user.js file as soon as the page loads or if you're using some type of bundler like webpack what's going to happen is your user and your script file are going to get combined into one file which gets downloaded by the user no matter what happens all of the user.js code and all of the script.js code is being downloaded as soon as the page loads now with dynamic module imports what we can do is actually make it so certain codes in our application only get loaded after our initial page load or they get loaded at some later point or they don't even get loaded at all let me show you how you can convert this code to use dynamic module imports it's actually pretty straightforward instead of using this import statement here we're going to use a function called import instead and in that import function all you do is you just pass it the name of the file so in our case it's called user.js so so far all we've done is called the import function and passed the file into it and this returns to a subpromise so we can use then on the end of it and this is going to give us all the information for our module if we have really quickly just come in here and console log out what this is returning to us you can see over here we get a module and it contains a default property which is our user class and this print user function which is our print user function so what we can do is actually destructure this so we can come in here and we can just say you know we're going to destructure this into an object which has a default property which we know is our user class and it has a print user function so now we have access to that user class and that print user function and it's pretty much the same content that we have here inside of this section and to make it even more apparent what you could do instead is actually take this user and put it inside of our parentheses here so we could say default as user this does the exact same thing so really all we're doing is we're taking this mapping here and we're moving it down into a destructuring mapping down here if you're unfamiliar with how destruction works i have an entire video on it i'll link in the cards and description for you but now that we have that done we can essentially copy this code paste it inside here comment out everything up here now we click save and you can see we get the exact same result but now we're doing a dynamic import instead of doing a static import the big difference is is that this is only going to get loaded when we call this import function so if we were to come in here and put like a set timeout and we you know wrapped this inside of a set timeout and we said that our set time amount is going to be you know five seconds for example well what's going to happen is our page is going to load and then five seconds later it's going to download this code for our user.js and then it's going to run all the code inside of it and you'll see it'll print out kyle cook after that five second delay and if you have a bundler for example what's going to happen is it's actually not going to combine together your user.js in your script.js it's only going to download your script.js and then after five seconds it's going to download all the code inside your user.js file this is going to lead to quicker speeds for loading your pages and that right there is essentially the basics of how this works so let me jump into probably the first most useful example of this and that's the idea of splitting up your code into different bundles so you only have to download the minimal amount of code at first and then if you need extra code you'll download it as you go it's very similar to what we have here let's just imagine that normally we have some import that's just called setup admin user and we're just going to import that from some random class we'll just call it dot slash admin dot js it doesn't really matter what it is we just have some admin related javascript and we're going to call a function called setup admin user and what this is going to do is just going to set up all of our admin user stuff so it's just going to be like making our fields editable that aren't normally editable for certain users what we want to do is first to make sure that we are a user so if our user is an admin then we're going to call this function right here otherwise we never actually care about this code well if you're just doing a normal import like this what's going to happen is this admin js code is going to be downloaded by your user even if they're not an admin user it doesn't matter every single person downloads this code and then only the admins are actually going to run the code so for most of your users you're downloading all this code in admin gs which could be a huge file but most of the users are never actually using it this is an ideal place where you want to use a dynamic import because you don't really want to download this code unless the user actually needs it so instead you could move your import inside of here we're going to import from admin.js and we're going to use that then syntax and we just want to make sure we extract out here that setup admin user function and then we're going to call that setup admin user function and we don't need the import out here now what's happening is only if we are an admin user then we're going to download this code but if we're not an admin user it's as if this doesn't even exist so it never actually downloads this code so if you have a huge javascript file that only a few users are going to use this is a great use case where you want to dynamically import that because most of your users don't actually care and don't need this code but the few users that do need it they're just going to get it downloaded as soon as the page loads already speeding up page load times is the most obvious use case for this but another use case is when you have a bunch of different files that you only really need one of so you only want to download one but without dynamic imports you have to download them all so translations are a great example of this as you can see we have a bunch of translation files we have english spanish french as you can see in each one of these we have an object for translations we're translating hi here into spanish french and english and you can imagine you know you have 20 different languages and each one of these files is massive because every single piece of text in your website needs to be translated so these are big files and there's lots of them and right now we're importing every single one of these files we have our user who has a local so this user is an english user and then we're just checking to see what locale the user is if they're spanish we use spanish translations if they're french we use french translations and we just default to english so that way if it's a translation we don't have supported we're just going to default to english as you can see it prints out high down here because we're printing out the translation for hi if we change here to spanish you can see it prints out ola we can do french here it's printing out the french version and if we do something like russian which we don't support it just defaults to english now the problem with this is we're downloading all the translations for every language we support and again like i said this could be massive files that you're downloading instead we want to just download the files that we need what we can do instead is use a dynamic import and dynamically create the actual name of the file so let's just go down here a little ways we're going to use import what we want to do is we're going to use string interpolation to create our file name dynamically as we know you can see here the file name starts with our user's locale and then ends with slash translation here so i'm going to copy the second part of this and we know that it starts out dot slash then it goes locale and then it goes this so we can just say in here user dot locale and this right here is going to create a string that has the user's locale at the beginning and then the translations.js so it's only going to download the one individual file that we need let me make sure i put that back in there so now what we can do is we can say dot then and this is going to give us our translations so we can just say we want to get our default out of here which is our translations there we go and then inside here we can use those translations so now we actually have the translation so we can say translations dot hi and that's going to print that out so we'll say console.log oops translations.hi i can comment out all this code up here and now if i save and make sure i change this to something like english that's actually going to work you can see it prints out high but we don't have that default right now what i want to do instead is just make sure that for the default if we don't actually have a file to be downloaded we use this english version instead a really easy way for us to do that is just throw in a dot catch here before our dot then this dot catch is going to get called any time that there's an error so if there's an error locating this file if it doesn't exist it's going to call this dot catch and inside this dot catch all that i want to do is just import our english file so we're going to say english translations.js and then our dot then is going to take in this english by default if our translations does not exist otherwise it's going to take the translations for the current locale let's delete all this code here so we're just left with our user and this dynamic import here i'm going to save you can see english works correctly we change this to spanish you can see that it prints out ola if we do something that doesn't exist such as russian you can see we can ignore this error because it's just a devlog thing but you'll see that it says hi right here and that's because it failed to find the file with the russian translation so it instead caught the error here and now is importing the english version and then down here it's using that english version as our fallback this right here allows us to download only one file which saves on memory space it also saves on download speeds it's super useful now this final example i want to talk about is going to be similar to the previous example but the focus is going to be a bit different the last example was all about saving not only time but also saving memory because instead of downloading hundreds of massive files we're only downloading one file this use case is more about saving time and memory but only if we need it take for example if we have an array of different shapes and we built out a complex rendering engine where we have hundreds of different shapes that we want to render out well normally what we need to do is import all the rendering engines for every single one of these different shapes and then we need to check what shape it is and then render it out as you can see we have two rectangles of the triangle it's printing out over here we rendered some rectangles and triangles because all these functions do is just print out render triangle or render rectangle pretty straightforward but with dynamic module imports we can make sure that we're only importing the files that we actually need when we need them so if we only ever render rectangles or triangles we don't actually import the other module so to do that we can just change this for each loop here instead we just want to do a dynamic import and inside of this dynamic import we're going to make sure we use template string here to get our shape dot type and we're going to put our dot slash at the beginning and our dot js at the end and this is going to get us the file we need then what we want to do is get to that default export out of here which we're just going to call render it doesn't matter what we give it for a name and then we're just going to call render with our shape and now if we save this you can see we get the exact same result it's rendering rectangle then triangle and then rectangle we don't need these imports up here anymore which is nice and the best part is if we only ever render rectangles there's no triangles to render we're never going to import the triangle js file which is just going to save us time memory and space also something that's pretty nice is that we can actually use async await with imports really simply so we can make this an async function we can await this and then instead of using dot then we're just going to take our default out here and we're going to call it render set that equal to waiting for this we get rid of all this code down here all of the dot then and we can just call that render function with our shape this is going to give us the exact same result as you can see on the side so if you like async await you can use it with the import syntax super easy and if you're unfamiliar with async await i have a full video on it in the cards and description you can check out now if you enjoyed this video you're going to want to check out my javascript simplified course where i cover concepts like this in depth so you can understand everything you need to know about javascript if you want to check out that course i'm going to link it down in the description for you and with that said thank you very much and have a good day
Info
Channel: Web Dev Simplified
Views: 92,010
Rating: 4.9731827 out of 5
Keywords: webdevsimplified, dynamic module import, dynamic module import js, dynamic module import javascript, js module imports, js modules, es6 modules, node modules, nodejs modules, node.js modules, node js modules, module import, import module, import module js, dynamic modules, dynamic modules js, dynamic modules javascript
Id: ddVm53j80vc
Channel Id: undefined
Length: 11min 36sec (696 seconds)
Published: Tue Jul 13 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.