An Intro to CSS in JS with DIO by@thysultan

An Intro to CSS in JS with DIO


function Hello () {return {render () {return h('h1', 'Hello World')},stylesheet () {return `& { color:brown; font-size:40px; }`}}}



DIO[1] is a 10kb framework much like React, though once upon a time it was 6kb and every single Kilobyte added has been a tug, because on one hand i wanted the framework to be small enough that it avoids the problems faced with page weight and on the other i wanted to allow components that can ship with closely coupled css.

So two weeks ago i came to the conclusion that if this was to work i would probably need to parse css because it is naive to think that you can write a css parser with Regular Expressions right? Hint: if you writing a parser in javascript `.charCodeAt` is your friend(comparing numbers is fast). Now, the idea behind `stylesheet()` is similar to the idea behind the `render()` method, one returns a virtual node the other returns a string.

Thus given the following

stylesheet () {return `&{ color:brown; font-size:40px; }`}

It’s a far cry from cryptic but below is what you would expect DIO to generate.


This generated css is cached to be used for all instances that extend this component though for performance reasons this process is detached from the normal virtual DOM diff reconciliation.


Although everything in css is global unless explicitly declared otherwise, we kind of want to get away with writing the following code without having to filter it with id’s and classes that we will then have to manually attach to our components and keep track of naming conflicts.

stylesheet () {return `@keyframes slideIn {from { transform: translate(0px); }50% { transform: translate(200px); }100% { transform: translate(0px); }}

    [@media]( "Twitter profile for @media") (max-width: 600px) {   
        & { color: red ; }   
    & { animation: slideIn 3s ease infinite; }  


//,output (playground)

Behind the scenes DIO generates the following

@keyframes HellojfirdslideIn {...}@-webkit-keyframes HellojfirdslideIn {...}

@media (max-width: 600px) {[scope=Hellojfird] { color: red; }}

[scope=Hellojfird] {animation: HellojfirdslideIn 3s ease infinite;-webkit-animation: HellojfirdslideIn 3s ease infinite;}

creates a style element and attaches the somewhat cryptic attribute `[scope=Hellojfird]` to the corresponding components dom node.


Hacker Noon is how hackers start their afternoons. We’re a part of the @AMIfamily. We are now accepting submissions and happy to discuss advertising &sponsorship opportunities.

To learn more, read our about page, like/message us on Facebook, or simply, tweet/DM @HackerNoon.

If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!

react to story with heart
react to story with light
react to story with boat
react to story with money

Related Stories

. . . comments & more!