juanca / blog

1 stars 0 forks source link

CSS Modules #6

Open juanca opened 4 years ago

juanca commented 4 years ago

Outline:

juanca commented 4 years ago

Background information:

Web development gets increasingly complex and cumbersome with the size of a codebase. JavaScript fixes this problem through a module system. For Webpack, a similar approach can be applied to CSS with a CSS loader: every JS file can specify a CSS dependency (or more!) and it can be processed with Webpack. This makes it easier to figure out which CSS file is used with which JS file. No longer is it necessary to keep track of which CSS dependencies are required in an page because the JS entry can specify its CSS dependency.

Here is some example code to showcase the above:

/* app.css */
.appContainer {
  border: 1px solid black;
}
/* message.css */
.messageContainer {
  font-size: 14px;
}
// message.js

import styles from 'message.css';

export default function Message(props) {
  return (
    <p className="messageContainer">
      {props.value}
    </p>
  );
}
// app.js

import styles from 'app.css';
import Message from 'message.js';

export default function App(props) {
  return (
    <div className="appContainer">
      <Message value="Hello world!" />
    </div>
  );
}

With this setup, it is no longer required to write a CSS entry with all the styles needed for the page because each JS file will declare its required CSS. However, there is some cognitive overhead to:

  1. Keep the class names mirrored because the values are hardcoded between the JS and CSS file.
  2. Manage the styles associated with each hardcoded class name.