Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Import JavaScript Variables for Styling with CSS-in-JS

    Oleg IsonenOleg Isonen

    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.

    scssSCSS
    cssCSS
    javascriptJavaScript
    Code

    Code

    Become a Member to view code

    You must be a 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
    Transcript

    Transcript

    Instructor: 00:00 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.

    00:13 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.

    00:32 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.

    00:50 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.

    01:04 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.

    01:20 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.

    01:40 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.

    01:53 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.

    Discuss

    Discuss