Webpack 5 CSS Walkthrough: Sass, PostCSS and more!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome to swashbuckling with code i'm jimmy cleveland and in this episode we're going to be covering a bunch of different ways to get css working in webpack we're going to start by creating a webpack project and then getting css imports to work right away then we'll add some spicy sas support as well as source maps so that you can see your original code in the browser i'll show development and production builds with minification so that your users can download less and have a faster experience overall we'll cover inline styles being injected into the document by our javascript bundle as well as an alternative creating an actual css file from our output in the last segment we'll add post css so that we can modify and extend our final css output that'll allow us to do some pretty cool stuff like auto prefixing poly filling or fallbacks for cross browser support and then we'll read from a browser list rc config file in case the defaults that post css give you are not covering enough browsers for your user demographic finally we'll top it all off with a quick addition of tailwind css just to show how easily we can add things to our pipelines now that it's all set up my goal with this video is for you to walk away with some confidence in the multitude of different flavors that you can set up for css inside webpack all right time to code [Music] we're going to start with creating a project here and i'm going to be cruising through this until we get to the css specific details but i do want to show you me setting it up from scratch just so that you know but if you're interested in me going through each package that is required for webpack for a basic setup to work with babel and going through all the different snippets of code in detail i have a video that's better suited to that that i'll link in the description and a pop-up so feel free to check that out if you are interested in that but let's move on here so let's create that directory i'm going to name mine webpack styles you can name it whatever you like and then we'll cd into that directory and from there we're going to init up an npm project or package json dash y is to say yes to all the answers so you can just skip answering them individually and then we already know that we're going to use webpack so we'll just add that as a dev dependency we're going to do webpack and then if you use webpack and you're going to run the commands for it you need the webpack cli those go together now that's finished we can open this in our favorite editor whichever you prefer mine opened in a different window so i'll bring that over here and we can see what we have here is a package.json with just these two packages so that's good and then what we need next is we want to create a source folder with an index.js and if you select to create that as a file in vs code it'll actually create the whole path for you just so that you know in this file we can do is we can just make a variable real quick so we'll say const headline equals welcome to the web page or something dumb like that okay now with webpack you don't need a config if you are going to use the defaults which is the source index.js as the entry point so that's why i've placed it there if we come back to our terminal we can run npx webpack and if you're unfamiliar with that npx is a way to go and get the most recent or current version of a package and run it or it'll use your local one if you have that set up so you can see that this built properly we do get this warning that tells us that the mode option has not been set and that's under uh that's expected we are going to be building in production by default which means that you'll have everything minified and mangled and all that good stuff now if we go back to our code we'll see that it has created this dist folder and a main.js and you can see that it's empty which might surprise you if you're not super familiar with webpack but all you need to know is that in the end if it's for a production build it's only going to put into the final output file what it actually needs to run so what we can do here is say document.query selector because we're going to be running this in the browser we can find the first h1 tag and then we can do no i don't want text content thank you i want enter text and we can set that equal to headline so now if we go back we run our mpx webpack again we come back here we can see that our main js has built out that script it's put it all together notice that it didn't need to keep the variable or anything like that so just a real quick rundown of that now let's get on to adding some styles so we'll create our css file here and i'm just going to call it style.css it doesn't really matter because we're going to import it by name so here we'll just set some basic styles here so i'm going to do background color hey why'd you go away we're going to make that salmon and then we're going to make the the default color of everything moccasin for fun and then we're going to take the h1 tag that we're going to create and we're going to do fz for the shorthand and i think we'll do 68 pixels and then from there we'll just say can i do tac here yeah nice cool so text align center and then we can go over to our index file and we'll just simply import that um we don't need to actually name it because we are just trying to raw load all those css variables we're not going to like use that variable or anything like that or those css styles i should say so we can just say style.css and that will load our styles onto the page here and that'll make a little bit more sense if that's confusing to you once i actually render it out so just bear with me for a moment so if we go back to terminal once again we go to build we can see that we're getting an error and you want to look here first to the side of the error where the file which file it happened in which is style.css it tells us that it's an unexpected token and it says and gives us this little hint that i think could be a little bit better honestly but at least it points us in the right direction it says that you need an appropriate loader to handle this file and that is true and you can see that it's just it's getting hung up on basically css syntax because it's not javascript in this case so let's add those loaders okay so we're gonna need um we're gonna need css loader so that's gonna be our loader to tell webpack how to deal with this type of syntax or file and then we're also going to use style loader because with css loader that will build it but it won't give us a way to really output it and so style loader is a way to inject inline styles onto the page and i will show you how to create a css file separately afterward but we're going to stick with style loader for now as that's a pretty big norm so now that we've done that we need to actually set it up in our webpack config so this is when you do actually need a webpack config so webpackconfig.js is what we're going to create and then the normal format for this is you're going to have a module exports which is going to be an object oops sorry and in here you're going to have a property called rules which is going to be an array of rules and each one of those is typically going to be an object and it's you can think of this as like each one is a rule for to tell a webpack how to process a certain type of file so to tell it what type of file you use the test property and typically you're going to use a regular expression i don't even know if it takes another format so i'm making a regular expression that's case insensitive here and then i'm going to do css and i'm going to say it ends in css but we can do a little escape this dot here just to say i'm looking for anything that ends in a dot css cool and then from there you're going to use the use use the use and what that does is it makes it so you're saying what how do you want me to handle this like what is going to actually handle this type of file so we'll say css loader is what we're using and i'll show you that just working first and then we'll add style loader so that will actually get us past this error i like to do a little bit of a red green approach to whenever i'm demoing stuff to red green just means that i want it to fail first and then i want to fix it it's kind of like a test driven development methodology so that you can just see what's the minimum that's needed to run something so here we ran webpack and it says invalid configuration object webpack has initialized using a configuration object that does not match the api scheme okay so oh you know what that's great um it's not rules yes it is rules oh haha you know what it actually is here i'll leave this mistaken because this is funny so it's module first is the first thing that we need there's a module key that has rules and that's how you're going to handle each of those let's try to run that one more time there you go beautiful so now uh it will build and everything and let's actually take a quick look at our output here we can see that it's now has this big old uh minified bit with a lot more code so you can see it's it's uh it is putting in a bunch of code that essentially see can we prettify this let's see format there you go so we'll just format that real quick so that you can see the final production version of it and you can see there's a bunch of javascript that's been added and it's essentially like how to deal with all of this css but you can see the css inlined as a string here you don't need to understand how this works i just think it's a good idea to get a little bit of exposure early on so it's not so intimidating or or you know anxiety of what's going on under the hood and then you can kind of build up as you go um you know taking a a look at each of these things so don't think that i know how all this code works i do not but it's nice to every now and then when you have a little bit of extra brain power come and take a look at each piece and get a little bit more familiar one step at a time that's just my two cents on it okay so we can see that that's working and like i said uh this does output it but it doesn't give us a way to put it on the page and so that's where we'll add a style loader in front of that there and that will do it for us and in order to show that we'll actually need an index.html file i'm going to manually create this in the distribution folder and the reason i'm doing that is just for demo purposes it is a common practice in some of them sometimes you'll just generate out your html files and a lot of times you won't write your own html if you're using view or react or you know any any sort of utility library or framework it's probably going to be processing all of your html for you you'll just have like the starter file and so this is what it'll kind of look like here i'll just use this little snippet here here we'll make we'll make a title why not it's just webpack css examples or style examples and then here this is where you normally have like your div with an id of root but we're just going to make we'll make a container class and then we will make an h1 tag and in that h1 tag i'm just going to do some nonsense here it doesn't matter what because our script is going to override that and that's how we'll test that our script's actually running but in order to get the script here we will say script and you can use the snippet for source and then we'll say oh yeah let's go grab our main js and run that so i could set up a dev server at this point but for this demo we're just going to raw load this index html in the browser so i'm going to do reveal and explorer and then i'll just pop this open here and here you can see it loaded up i'm on wsl so it's got this funky little thing in front of it on windows you can see it running our script but not loading our styles yet and i believe that's because we didn't rebuild after i added the style loader in so yeah cool so let's go back to the terminal and we'll run npx webpack again and we're gonna add a build script for that right after this and so now that that's there we should reload this and every time there we go so we can see that our styles came in and if you're curious where those styles come from exactly you can check in the head and what it's done is it's injected the style tag at the top of the head and that's how it works so you can also inspect just as a side note you can scroll down here to the h1 and you can't see this because my head is in the way um but there we go that work so here with the style tag here you can click on this style tag and it'll jump you up here so let me actually show you that again if you go to the h1 you can click on this and it'll take you up to that tag cool all right now that wasn't too hard right so next what we'll do is we'll add sas or scss to it so let's start from a code first approach here and then we'll add uh in the terminal the things that we need so we want to now uh have access to scss so we can rename this file to be scss and that means that wherever we import it in this script we also want to change that to scss and if we try to run this in the terminal of course this isn't going to work so yeah you can see that we're getting the same errors before it doesn't know how to process it just because of the file extension and that's really because in our webpack config we only told it to look for this type of file so we of course could add this scss and then that will work but let's um well let's make that work and then i'll show you the next step but we want to go to package.json real quick since we're doing this a bunch i'm going to add a build script here and then i'm going to just make webpack that's the thing and i'm also going to add a build watch you can name them whatever you like and this is going to be a webpack and then dash dash watch here okay so the first thing that i'm going to do is run over and show you that if i do run build it's the same thing as our mpx webpack and that's just a little more normal because you're going to be using this script all the time and you want it to be able to build you know on your server that ever compiles it and you can see that it actually builds now but we're not using any scss so you know that's not really that great of a win so let's do something here let's create a variable we're going to name it a light text and then uh we'll make that our moccasin can't type for a moment and then down on the color um what we'll use here is we'll just be able to do light text and then we can also scope this underneath this here because that is another functionality of sas i'm just throwing in a couple things that would normally cause our css to fail so we haven't actually added any loaders in yet so just really quickly if we just do npm run build it will build surprisingly but then when we go back to the browser you can see that it's just tried to load in this non-viable syntax that it can't read here i wonder if we get a console error from that no we don't okay so let's add our loaders in now so in order to get sas working we're going to need to install sas which you can also do with dart if you like i'm doing node sas here and then we're going to do um sas dash loader and that's actually all we need pretty cool right and then come over to here and if we go to our webpack config we can tack on the end of this we can do a sas loader and that's all we need so now let's do npm run build coin watch and then we'll go over to the browser we reload and it's working again and you can see that our output is just a regular old css even though it's inlined it here like this it doesn't have those variables or anything so in the end it's compiled sas into css and that's how that working and now that we have watch open well i can show you i could make a colon root tag here and then say that i want a main e g you know i'm going to use a css variable here just to show this and i'm going to make this that sound salmon that we made before and then for the background color i'll do var and then we'll use that main vg and all i have to do is save that and if i come back over to here it'll still work and in fact let's actually change it to something so let's do like medium purple or something like that okay come back over here reload there you go now you can use webpack dev server if you want to get that live reloading but we're not going to cover that in this video here okay so let's revert that back here so now what if you wanted to process both regular css files and sas files for some reason or you want to handle both types of syntax sass and scss or whatever if you want kind of a global fix here let me just show you this so if i add let's just do a you know woof.css page and pretend in it i'm just going to make up a rule that the regular font size is like 18 pixels or something like that okay it doesn't really matter the point here is that what i want to do is go to my index.js and i want to try and import that and if i try to import wolf.css we have set it to where it will only look for scss here and want to be able to find both so if i come over here shut this down real quick and then i'm just going to run npm run build you can see that has that failure as expected and that's going to be the same error and so let me show you how you can do this real quick it's pretty simple what you can do is you can say all right i let's uh start at the top here i want to wrap this whole part um because i know it's always going to end in an ss for css or scss and i can actually say it either needs to be sc or it needs to be c at that point okay and then if i run a build here that will run now and if i wanted to be able to support let's say sass as well i can add a bracket here which is interesting and what that will do it'll say uh it's got to start with an s if it's going to be on this side of the pipe and it could be an a or c here and then otherwise it's going to start with a c and then ss so that's just kind of breaking down the regular expression that you might see sometimes in case you're unfamiliar with that type of stuff so that'll make this you know work pretty robustly for all different types so next let's show uh creating an actual css file in here rather than just doing the uh the inline styles so just a quick note on that when you're using webpack very commonly it's used for single page apps nowadays and that would be the standard format for injecting that you know you have one entry point here and it's okay to just have your styles you know inlined here or you could have separate files if you like that's fine as well for css files but webpack also does support multiple entry points in the config and i'm not going to cover that but i just want you to know that if you set up your entry points in here you can point to multiple different js files and then you can import them individually so you could have like an about page and that about page loads and about.js script and that loads that script loads the about.css file or whatever so just so that you know um it doesn't all have to be this one entry point i'm just showing you the most common way to do this so what we're going to need next is uh we want to add a new package here which is going to be mini css extract plugin i always forget the name of that one and this used to be the extract text plugin uh if you're familiar with that at all but since i think webpack four they've switched that over and so this is gonna be our first plugin so we're actually gonna need to bring it in and it's common to use this uppercase but i don't really know why probably because it's like a class or something and then we're going to do extract plugin and that's equal to a require statement here and then that's going to be this mini css extract plugin and then you need an extra property here you're going to do plugins and you from there we'll new up this constructor here if you don't know what that means don't worry about that it's just the syntax and i think you can pass some options here but i never really need to so from there you're almost done except you're going to swap out your style loader and instead you're going to do mini extract plugin dot loader and pass that in and that's the whole setup for it so now what you'll see is next time i build we're going to have a actual css file here instead of the injected styles see it created this right here and you can see it's all uh minified and beautiful and then if we go over to the browser you can see that we don't have it yet because we haven't imported it and so what we'll need to do is just run it like a regular css file at this point so we could just say okay let's make a link that is a css type and then that will just point to main.css and you can see without any configuration it just by default shows main css to be the output there which is pretty cool and then now if we go back to our browser boom everything's working just like usual and the big difference we're gonna see here is that it doesn't have those styles in the head anymore it actually is going to have a css file let me okay so i'll move that just a little bit so you can see here this main css is what it's going to be so you click that and then here you go and you can use this little click button to to purify it and it's giving you the final output now you don't have to output a css file if you don't want to just kind of depends on use case i'm just showing you the two different ways that are the most common that people want to do so this is a pretty good segue into source maps because what if we have a bug in our code and we want to know like where it lines up with the original code like this is actually just the output css so what we can do for that is actually pretty neat we only need to go to our webpack config and you can add this property called devtool and if you set that to the string source map that is going to generate source maps out now so we run that build go over to our browser and we'll reload here and we close that go back to the elements tab and then you'll see now uh we actually have an scss link with the proper line number so that's pretty cool so if we click that it will take us to the scss version where in comparison let me show you this one the css version you can see that it kept our css variable but not our sas variable and it also doesn't have things nested the way that they are it's the final output whereas uh where did that go go back here and whereas in this one it will reflect our actual code and the different line numbers it's just a lot easier once a file gets really big in order to be able to track down bugs or just to see quick references if you're trying to look something up in a file or something like that okay so that was pretty simple right just a quick note about source maps we should actually probably go to a webpack source maps that was a weird search and we go to this just so you can see i had a hard time learning this at first or figuring out like what type to use and from what i've learned a source map itself is kind of the most robust one as far as it it works in development and in production and it also is the most like accurate to line numbers and all that the problem is that it's slow and it is nice of them to put this documentation in here to show us like the different speeds in this table but i feel like it's a little bit overwhelming to look at all these and just have no idea which one to use so the things the main things to think about are just whether you want a production or a development only source maps and that's a big debate online the main arguments one way or another are essentially that if you put your source maps into production it will allow you in your production code to actually track down bugs in the final format and that's you know pretty powerful and useful at times if if that's what you need now but some people you know argue that you might want to hide your code you know you don't want people stealing your codes you're going to mangle it all up and minify it and all that stuff or it's a security thing security through obscurity and um yeah i don't really have a stake in the argument either way i think it's fine to leave it in both and some people think that it i used to think this that it adds extra file size to it to have the source maps because if you look in your code it does have to generate out this map file and so that makes the user download more but that's actually not true as far as i've learned is that the the source maps aren't downloaded until devtools is actually opened so even if you look in the network tab here it's showing what the user normally downloads in their network experience and that source map file is not in here so yeah that's not an issue it's really just a matter of whether you want your source maps to only be in development or only in production so that's how you can choose like which type you need but if you're not sure just stick with source map and then deal with that later so end rant let's move on so next up is going to be post css now if you're not familiar with post css i'll give a quick little explanation to it so it is a way to make final modifications to your css output and the most common uses that people are familiar with would be something like auto prefixer so when you're using uh you know modern css style rules and you need cross browser support for like fall backs and stuff like that auto prefixer will go and add those little dash dash webkit or dash dash ms or all those flags you can also use it for polyfills or fallbacks in some cases and that's what we're going to start with so let's pop on over to a terminal and let's just install what we need first here so we're going to add post css and then we're going to add post i always want to put a hyphen there css loader and then finally we're going to have a preset here so we're going to do post css preset env those are the three packages we're going to need here and this is a really powerful step that allows you to do a lot of really cool things you know past the point of just writing styles in a certain way you can do a lot of transformations and stuff it even allows you to do linting if you're familiar with that with style lint and all that stuff so in order to set that up here what we can do is tack onto the end of this chain you can see we're kind of like composing these loaders together one after another and it's pretty neat format here and so what we're going to do is post css loader is going to be the last step here and you can actually set up post css loader like right here so if you're not familiar with loaders in general you can actually open up an object at any point and then you know select your loader and all that stuff and then you can pass an options config to it but i like to keep this nice and clean and readable here and so i'm going to do kind of what the standard convention is for post css is i'm going to create a postcss.config.js here and what that will allow me to do is make a sort of config object that is just related to post css and well let me show you how to do that and then i'll kind of explain my take on that so we can just do a require here and then we'll just do that post css preset env that's all we need all right and actually we need module exports equals there we go and that's all we're going to need and then how this works is that there's certain plugins like babel or postcss that when you pass this here they'll by default look at the root for a config file and so you don't need to actually pass any extra options if you want to just do that here the reason why it's nice and this is my take that i was talking about before is that i kind of think of this as like modularizing your configs because this webpack config can get pretty big and bloated full of stuff and i think it's nice to kind of think of it as like a series of operations that are happening and if you want to dig into how they work then you can go and look at this config file and we're about to do a browsers list to show that and that's really convenient to have as a config file here because both babel and post css both look at that file so if you have multiple things that use a type of config it's nice to abstract it that way as well that's just my preference but you do it however you like so what i want to show here is if we go over to our sas styles i'm going to start writing in a bunch of extra styles here so that we can see a post css in action and i want to kind of talk about the the defaults in the browsers that it hits so first i'm just going to add some silly stuff here let's say i'm actually going to move this h1 out of the body because that was silly in the first place but maybe we'll do like the container that i had created before and then we'll move this up here and then what i'll do is i'll say let's do padding one ram let's do display flex and then perhaps we'll do a really silly background linear gradient and i'm just going to be like to top black to white it's going to look terrible but let's do this for speed purposes i always do that one but semicolon there boom okay okay so now that i have a few uh styles here that i know aren't completely backwards compatible i'm going to show what happens when you run this through post css now the thing that you're going to want to know here is that it's actually a lot of things that you use in css uh the adoption rate's been a lot faster and so it's harder and harder for me to find things that need cross browser support or a lot of it and so what i think the default for post css is for this preset env is that it will go two browser versions back and then if if a browser has greater than one percent of traffic then it will use that otherwise it won't and you would think that that's pretty restrictive but most things actually work and let me show that here so now we can do npm run build again and now if we open our output this main css file we moved out to the side and actually that's not that useful to read so let's drop that back to development mode or for the first time and so let's say development that's what we want to set the mode to and you'll see right here that when i rebuild that it will output this in a more readable format so this isn't what you'd want to serve to your users of course this is just for you developing so now we can see that it has actually added from the original let's put these a little bit side by side so it has this background color and you can see that it did take out this but it added this this fall back here with the post css and but it didn't really change much else that seems to be like the only fallback that it added maybe to support css variables so let's actually add a browsers list rc which is a common thing that you'll do in order to get a little bit more backward support and i can show you post css actually working with the preset here so we're going to say browsers list rc and in that what we're going to do is say last two versions this is just the format for it so i want to support the last two versions of every browser and then i want to support greater than 0.5 percent oops and that is essentially going to say if a browser has more than you know point five percent of global uh traffic uh then we will support it which is pretty generous honestly and then we're gonna throw an ie10 into the mix uh that's what they show and some of their examples and i think it's a good one you know these so these are the this is the browser like setup that we want to support and what you're going to see now is if we go and rebuild that we'll bring this back up notice that we now have some auto prefixes here this webca flex ms flex and webkit gradient so these are the the prefixes and fallbacks that it was able to create for us and that's how easy it is it's pretty sweet and so now we we can say um i guess maybe if you're not familiar uh with this whole process it's that you know we it's expensive to throw prefixes and polyfills or fallback support for every single browser it's just too much for everyone to download and so by default the post css preset env is picking some what they consider to be very you know same normal uh amount of polyfills and presets for the browsers that people use it's like over 90 of traffic but if you're you know you're just in an unfortunate situation at your workplace where you need to support old browsers for some reason maybe your your clients happen to be a certain demographic that use very old browsers you can actually come in here and say yeah i want my browser's list rc to say that we want to support ie10 for example and what's cool about that is not only will your css do that but if you start doing babel to use like modern javascript it will use this same config here if you have that setup and so it will all your stuff will target those engines and so that's why it's nice to create this file this way so that was a lot of stuff with all that said and done we're in a pretty good spot right now we've got some a really good flexible setup and uh to to kind of demo uh how cool our setup is real quick just to wrap this all up i'm going to really quickly run through how we would set up tailwind because you know that's a new and up-and-coming thing and maybe in our pipeline we decided we want to start using that and we've actually got pretty close to having that setup so i'm just going to really quickly speed through that and in order to do that so i'll show you is let's close the css file so i'm going to paste in some stuff from their docs here that they have so this is just oops i lost my arrow there thank you and this is just a real quick if you're not familiar with it i'm not going to cover the syntax here it's just a way of using a bunch of class properties to you know style stuff with very minimal css you know love it or hate it it's becoming pretty popular so uh now that you have a tailwind syntax here let's actually go to our css file and do some of the stuff that they need there so what you want to do is go to the top here real quick and paste these in now you can see we have this weird at tailwind syntax that's obviously not going to build normally for us and then i can go to let's say i'll go to the h1 tag and i'll throw in a directive and you can see that this it has a real problem with this but this actually will build once we set up the plugin even though it's showing us the syntax error that's just the editor not being able to recognize it okay and you can use like an extension to be able to read that format okay so in order to do this now actually all we're going to need to do is npm i d tailwind css and then we'll pop over to our post css because it is a it is commonly set up as a post css config and we already have post css so we can say oh well i now want you to also require tailwind css and then we can go back we can run a build here this one's actually going to take a bit because it adds a ton of stuff okay so uh pop on over here and let's see what our final output css looks like and you can see it got huge okay so there's there's a ton of stuff that it just added into here and if we go over to our browser uh i'll reload and you can see i have this really ugly looking thing now that's because my background gradient and all that stuff but you can see i have this button here and this button here this isn't a really good way to showcase uh tailwind but i am showing uh just for the the point of speeding this up in brevity here that with just a few lines because we already have that set up and we understand our setup at this point hopefully we can just quickly tack on to it oh yeah i want to be able to use a tailwind so let's throw it in the pipeline and i think that's pretty awesome so i really hope that this has been informative for you you know please let me know in the comments if you have any suggestions for future topics or anything like that or if you think some of the things could have been made more clear or any other general criticism i really appreciate it you know my channel is just starting out and you know obviously there's a lot of room for growth and i've got great plans for it so i hope you'll stick around for future videos and i'll see you then you
Info
Channel: Swashbuckling with Code
Views: 14,131
Rating: undefined out of 5
Keywords:
Id: SH6Y_MQzFVw
Channel Id: undefined
Length: 37min 26sec (2246 seconds)
Published: Mon Dec 28 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.