02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext Video

Dynamically Building CSS Files with Webpack

In this tutorial, we’ll learn how to dynamically manage CSS in React projects using Webpack. This process involves setting up CSS Loader and Extract Text Webpack Plugin to compile and extract CSS into a single file. By the end of this lesson, you’ll have a streamlined setup for handling styles in your React projects.


1. Setting Up the Environment

Before we dive into SaaS, it’s essential to get CSS working dynamically in React using Webpack. Let’s start by installing the necessary packages.

  1. Open your terminal and stop any running development servers.
  2. Install the following development dependencies:
    npm install --save-dev css-loader extract-text-webpack-plugin
    
    These tools help Webpack process and bundle CSS files effectively.

2. Configuring Webpack

To handle CSS, modify the Webpack configuration file:

  1. Import Extract Text Plugin:
    At the top of your webpack.config.js file, add:

    const ExtractTextPlugin = require('extract-text-webpack-plugin');
    
  2. Add CSS Loader:
    Add a new loader rule to process .css files:

    module: {
        rules: [
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: 'css-loader'
                })
            }
        ]
    }
    
  3. Include the Plugin:
    Add the ExtractTextPlugin to the plugins array:

    plugins: [
        new ExtractTextPlugin('app.css')
    ]
    

This setup processes any .css file you import and compiles it into a single app.css file.


3. Creating and Using a CSS File

  1. Create a CSS File:
    Inside your project’s src folder, create a file named app-source.css:

    .custom {
        background-color: #f0f0f0;
        color: #333;
    }
    
  2. Import the CSS File:
    In your App.js or main component file, import the CSS:

    import './app-source.css';
    
  3. Apply a Class:
    Use the CSS class in your JSX:

    <div className="custom">
        This is a dynamically styled component.
    </div>
    

4. Testing the Setup

  1. Restart the development server:

    npm start
    
  2. Open your browser and inspect the changes.
    If everything is set up correctly, your CSS should be applied dynamically, and the styles should be extracted into the app.css file in your build folder.


5. Debugging Common Issues

  • File Not Found Error:
    Ensure the path to your CSS file is correct when importing it.

  • Syntax Errors in CSS:
    Check for typos or incorrect CSS properties (e.g., don’t include quotes for non-string values like white).

  • Browser Not Reflecting Changes:
    Clear the browser cache or perform a hard refresh.


Conclusion

You’ve now successfully set up dynamic CSS handling in React using Webpack. This foundation prepares you for integrating more advanced tools like SaaS. In the next lesson, we’ll explore SaaS variables, mix-ins, and much more.

Video Transcript

00:00Welcome back to a new section
00:02where we'll be exploring SaaS
00:04and really adding a powerful new skill into your bucket
00:08of creating user interfaces.
00:10So the first step is we're gonna show you how
00:13to integrate CSS into any project that is a React project.
00:18And once we've done that, we'll move on into SaaS itself
00:21as we explore the creation of SaaS variables, how
00:24to import external SaaS files,
00:27and even how to work with SaaS mix-ins.
00:29Now in the next section we'll do a little bit more SaaS.
00:31You're not gonna get a become a master sasser,
00:34but you'll definitely have enough skills to start working
00:36with it and start exploring it as soon
00:38as you finish the section.
00:40So let's jump right into our first lecture.
00:42'cause in our first lecture we're gonna be dynamically
00:44adding CSS files with the help of web pack.
00:48And that is basically done using the CSS loader
00:51and extract text web pack plugin.
00:53We'll take a look at both of them, how to work with them
00:55to get to create a dynamically loaded up CSS file.
01:01Alright, we're almost ready to move into SaaS.
01:03An incredibly powerful and interesting
01:06and very cool pre-processor for CSS.
01:10But before we even do that, we really need the help
01:13of webpac to get even CSS to run in our application.
01:18So to do that, I'm gonna go into my terminal
01:20and I'm just gonna go ahead
01:21and stop the server that is currently running
01:24and I'm gonna go ahead and install a couple of packages.
01:27And more explicitly I'm gonna install two packages.
01:30So I'm gonna go ahead and NPM install,
01:33I wanna save it into the dev environment.
01:35And I want a new loader, which is called CSS Loader, but
01:38because I want to create something a little bit more fancy,
01:40I'm also going to call for the extract text web pack
01:45plugin, a real, a real
01:49mouthful type of plugin.
01:51Okay? We're gonna see how to work with it.
01:53It's quite simple but incredibly powerful.
01:55So as it's installing, I'm gonna show you how do we get CSS
01:59to basically compile on the fly.
02:03So to do that I'm gonna go into my web pack, um, config file
02:08and I'm gonna go ahead before I'm actually exporting
02:10anything, I'm gonna go ahead and create a new cons
02:13and I'm gonna call it extract text plugin.
02:17Now you could call it whatever you want,
02:18but the most important thing is that you require the extract
02:24text web pack, plug in.
02:28Now we're not doing E ES six here because we're just not,
02:31although technically we could in this version of
02:35node js that I'm working on.
02:38But just for the sake, if you're actually not running on the
02:41latest version, then we will still work.
02:43So we're, we're doing the not ES five per se,
02:46but this is the way node js natively would
02:50load up external plugins.
02:52So we're loading in that extract similarly to
02:54how we use the extract command import and export
02:58In ES six.
03:00Okay, so now that we have that text plugin,
03:02I'm gonna go ahead and add another loader.
03:04We already have one loader that loads in our JavaScript
03:07and compiles it down to ES five.
03:10I also want to load up anything
03:12that is a CSS file dynamically and this time around
03:17whenever, and I'm just going to copy this test,
03:19we're not gonna have any exclusions by the way.
03:22And whenever we have a file that is a DO css,
03:25what I would like to do is I would like
03:27to send it into our extract pub
03:30blah blah extract pub, uh, what am I doing?
03:33Extract text plugin.
03:35But as we're sending it through, I'm gonna also send it
03:38through the CSS loader.
03:39So the CSS loader will take that CSS
03:43and send it to basically a text.
03:45Basically it's almost like a text editor,
03:47the text extract pub plugin.
03:49Now this part is actually the loader part,
03:52so let me just configure it to be the loader.
03:54So we're loading in that loader, sending it, wrapping it as
03:58to the text plugin.
04:00And last but not least, I almost forgot to extract.
04:03So I'm using the method of extract,
04:05extracting out the CSS itself, converting it into a text.
04:10Now that I have it, the last thing that's left for me to do
04:13to actually get the basic construct working is to go ahead
04:17and add another plugin.
04:18And I'm gonna do that after our modules.
04:20So let me just break the line a little bit
04:23and here I'm gonna add a plugin, I'm gonna add plugins
04:26and this is gonna be an array.
04:27And I'm just gonna send in one plugin,
04:29which is gonna be a new extract text plugin.
04:34And literally I'm gonna go ahead
04:36and define the file name that I wanted to extract to,
04:38in this case I wanna call it app css.
04:41So all that hard work that was done
04:44is gonna basically make sure that anytime I try
04:46to import any CSS, it will capture it
04:50and extract it into the extract text plugin.
04:53And then all that's left for me is to set up that plugin
04:56to make sure that it's going to render into an app do css.
05:00Now, to actually be able to test it out,
05:02I'm gonna go into my browser
05:03and I'm gonna also add another link here.
05:05And my secondary link is just gonna go to the actual app CSS
05:10because it's gonna be a global item.
05:13I'm not putting it in a sub folder.
05:15Let's go ahead and test it out.
05:16And to be able to test it out,
05:18I'm gonna go into my app itself and I'm gonna go, oh, even
05:21before that I'm gonna go into my source
05:22and I'm gonna create a new file
05:24and I'm gonna just gonna call this, um, what am I, I need
05:28to call it a different name than app.
05:29So, so I'm going call it AppSource
05:33dot css.
05:35Lemme just save that as app source CSS in the same folder
05:38where my app is.
05:40And let's go ahead and create a little bit of HT ML.
05:42So how about we put into our html some really basic stuff.
05:47How about we go to our app
05:48and we extract out this extra styling
05:51that we've placed here.
05:52And if I just grab this whole baby
05:54out, I'm gonna cut it out. And
05:56What I'm gonna do is I'm gonna go
05:58and try to put that style in directly as another class.
06:03So I'm gonna set you a class to jumbotron an extra class
06:06that will be called, uh, let's call this bat.
06:09I have no idea why, but now let's give it a a fair name.
06:12So, uh, custom, how about that?
06:15So we have some custom CSS,
06:17lemme just go ahead and save that.
06:18And I'm gonna go into my CSS add custom.
06:22And our custom will basically, um, have a background image
06:29and it's also gonna have a color.
06:32Okay, so that's good as well. And we don't need all that.
06:35So we have here some custom CSS, which we're then importing.
06:39Okay, beautiful. Now last, last
06:41but not least is to actually also import it.
06:43So I'm gonna go into my import statements
06:46and I'm gonna just go ahead
06:47and just directly import it without calling it,
06:49I'm gonna call it app source, do css.
06:54And if I go ahead and save this, go back to my server,
06:57make sure that I start it.
06:59And if I don't have any errors,
07:00let's see if we're having any publishing
07:02errors, no publishing errors.
07:03Let's check if we have any errors in our application.
07:06And it's refreshing and, and, and then we have a error.
07:11Okay? So first of all, our error while compiling is it's
07:14trying to read the AppSource css,
07:19but without success, it's unexpected.
07:22It can't parse it.
07:23You may need an appropriate loader to handle this file type,
07:26which we sure do, that's why we've added it into our config.
07:29But I might have not clicked on the save button,
07:31which I do that sometimes.
07:32So let's give that another shot. Let's break out clear.
07:36Run it one more time. Hopefully Now it's gonna capture it.
07:39No errors here. Let's see if we, once we refresh,
07:43let's give it a refresh.
07:45Here we go. We're starting it warmer
07:47so we're not having an error, but
07:48because our HTML needs to be updated as well,
07:51let me click here on refresh
07:52because we also need to make sure that our,
07:54uh, CS s is updated.
07:56But if I go and check this file, the app do, if I go
07:59and check app dot css, let's see if we're getting our CSS
08:03that we've included and we sure are getting
08:06that CSS included.
08:07So the question is why aren't you working?
08:11Although technically you are working, it isn't
08:14that crazy stuff.
08:15So let's check it out so we have your custom. That is good.
08:19We definitely have also custom.
08:20And if we check out local host again on our
08:223000, 'cause now we're debugging.
08:24I have no idea why it's not working
08:26because it looks like it's creating it.
08:28We have your custom, uh, but it's not rendering out.
08:32Let's see if in our inspector, first of all,
08:34we see it's overridden.
08:35It's actually, what's the error? Invalid. Okay, that's good.
08:41Invalid property type. Beautiful.
08:42Okay, I already see what my problem is in our app source.
08:47I don't need here to have your quotes
08:50because we're inside a CSS and,
08:55And and what else is wrong here?
08:58Well, now it's not rendering at all.
08:59So let's see what's the error now? Fail to build not found.
09:03Cannot find file directory fi image folder.
09:06Oh, mm, that's interesting.
09:10What's actually happening is
09:11because we are in a file, basically it's relative,
09:15so I wanna tell it don't be relative.
09:17There's no relativity really going around here.
09:20And if we're ready here, let's also fix our white to be, uh,
09:23without the quotes because it's not a string in CSS.
09:26And let's go ahead and give it one more shot.
09:28And here we go. We have ourselves our CSS exported.
09:32And the beautiful thing about this is
09:34that we could have multiple Cs CSS files.
09:37That is, and anytime we click on import,
09:40we could then add it in dynamically building up our app
09:44CSS dynamically, which means that we could create a CSS
09:47for each button in each component separately.
09:50But we're not gonna do go down that path.
09:52We're actually gonna go a different path, which is sas,
09:54which we'll explore in the next lecture.
09:56Now that we know how
09:57to integrate CSS into a React project the right way.
10:02In this lecture, we saw how
10:03to dynamically add CSS into our file
10:06and we're ready to start moving into SAS
10:08because in the next lecture we're gonna also create SaaS
10:11variables, but beyond that, also plug in and connect
10:14and make SaaS actually work.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!