React single-file component proposal

Wed, 27 Dec 2017

When it comes to webdev, I’m predominantly a React man. However, I do like to keep an eye on the rest of the JS world and have dabbled with Vue. One of the best parts of Vue, in my opinion, is the SFCs (Single-File Components). These allow you to include the view template, script, and scoped CSS in one .vue file. This is then deconstructed and built using a Webpack loader.

The way React devs tend to deal with this is by using CSS-in-JS techniques such as Styled-Components. I’ve tried most of the different methods and almost always go back to using CSS files: it just feels like CSS wasn’t meant to live inside JS.

So I had a thought: wouldn’t it be nice if React used Vue’s single-file component method? What would this look like?

RSC

React Single Component, or, React-Script-CSS. Using all the cues from Vue, an .rsc file would look like this:

<script>
import React from 'react'

const Test = () => {
  return <div className="wrapper">Test</div>
}

export default Test
</script>

<style scoped>
.wrapper {
  display: inline-block;
}
</style>

The loader pulls out the style, and attaches data attribute identifiers to JSX (React elements) where it finds classNames.

I haven’t researched how Webpack’s (or alternative bundlers’) loaders are created yet but I do see this as quite a nice alternative to the CSS-in-JS debate. If any devs proficient in making Webpack loaders stumble upon this and fancy giving it a go, please let me know. Recently I’ve been playing with the new Parcel bundler, so I’d love to see this integrated with that.