Import and Render Style Partials from JavaScript Modules with CSS-in-JS

Oleg Isonen
InstructorOleg Isonen
Share this video with your friends

Social Share Links

Send Tweet

In this lesson, you will learn how to leverage JavaScript Modules to import CSS partials.

In JavaScript, partials need to be explicitly imported when exported by name, if a module exports styles by default, the styles and variables within do not need to be explicitly imported, just the module.

In this lesson, you will learn how CSS in JS partials are different to SCSS, how to use default export, and how to control the order of partials rendering.

Instructor: [00:00] We have two buttons. One is implemented using SASS, it is blue. The other one is green, and is implemented using CSS-in-JS. Let's have a look a SASS button first.

[00:11] We have this SASS button class, we import variables and we import sizes. Both variables and sizes are partials. This is how variables partial looks like, and this is how sizes partial looks like.

[00:28] SASS button large implements padding, font size and border radius, while SASS button implements color and background color. Now, let's have a look at the CSS-in-JS button. First thing you see is that we import sizes from sizes JS.

[00:46] Next thing is CSS-in-JS button rule. It contains same declarations as SASS button. Let's have a look at sizes JS. We have already learned how to import constants. Let's have a look at how we implement our partial.

[01:01] First thing is this export default statement. Export default defines the default export for this module. If you use named exports, you also need to import them by name as we did over here.

[01:15] If you have a default export, you don't need to name it when you import it. You can also have both default export, and named export in the same file. Let's get back to the button JS.

[01:28] The name over here can be anything. For instance, we can call it just, "S." We have imported our partial, and we have declared our button. Now, we have to render both of them. Here is how we render it.

[01:41] We create a style element. We insert it to the head of the document, and we use text content setter. The interesting part is over here, because here, we decide what is going to be rendered. As both sizes and the button are just strings, we can concatenate them.

[01:58] In our case, sizes will be rendered first and the button second. In the depth tools, we can see what SASS has rendered, and what we rendered using CSS-in-JS. Remember, the order in which we import partials here doesn't matter.

[02:13] What matters is the order in which we render them.