Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Import JavaScript Variables for Styling with CSS-in-JS


    As your application grows, you probably want to split variables into separate files. You may want to share those variables with a different part of the application as well as logically separate them so that you can find them easier.

    We will learn how to use JavaScript import statement for CSS in JS as a replacement for @import directive and what are the important differences for a large code base. We will also learn some basics about JavaScript modules.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: We have two buttons. One is written using sass or scss, and the other one is written using css in js. As you can see, we have variables and the button itself in the same file.

    As your application grows, you probably want to split those things in separate files. I know at least two reasons for splitting them up. First is you may want to share those variables with a different part of the application. Second, you might want them to be logically separated so that you can find them easier.

    To split them up, you can use an import directive in sass. The way import directive works is it takes this file and places its contents right here. Now, let's do the same for our css in js button.

    I have just moved the variables to a separate file called variables js. Let's take a look at this file. As you can see, we have the same constants we had before, but now, we also have an export statement.

    Export statement marks the constants so they can be imported later. This part of the import statement means we want to import all variables, and we want to use them from one vars object.

    In order to use them, we need to access this property on the vars object. We can also import each variable explicitly, we can use them without the vars object. There is a very big difference between import directive from sass and import statement from JavaScript.

    Imports in JavaScript implement a module system. When you import something from JavaScript module, you cannot overwrite it. Because it will throw a syntax error. This is good because you cannot accidentally overwrite them.

    Imagine you have a complex system with many files, and you import a lot of sass files. Any of these files could have overwritten any of these variables, and you wouldn't know where.