When building websites I have found that it is important to make everything I can into a reusable component, even if it is hard to imagine that component being used in a different circumstance. I can’t anticipate where something will need to be replicated in the future, and even if it only exists in one place there are advantages to building it as a component anyway. Here’s what I’ve done so far.
The websites I have been building are in Craft with templates written in Twig so my UI components go in a macros which I can then include wherever needed throughout the site. This does a few things for me:
- It forces me to think how similar components might be combined and reused throughout the site, increasing consistency throughout the project.
- It encourages me to abstract the data being passed into these components as much as possible, because the same component might be displaying data from different sources in different instances throughout a project. I like Andrew Fairlie’s approach of using an attributes object with defaults for a UI macro.
- Using macros is a rare instance where efficiency gains are undeniable.
- You only have to change code in one place. DRY FTW!
Multiplying the SCSS
A create a descriptively named SCSS file for each component and then include them all in my master style sheet when they are pre-compiled. Keeping each component separate makes everything so much easier to navigate. Every time I have tried to use more general SCSS files the questions about what belongs where get out of control, even if I’m not working with anyone else. For the size of projects I do as a freelancer I’m feeling with a few dozen components, and not the hundreds that a larger project might require so having lots of little component files is easier to scan and edit, not harder.
I have tried BEM in the past, but was confused when it came to styling elements that were nested more than one level. Once I got the feel of when to start a new block in nested situations the clarity of the naming scheme became more and more attractive. Using a class naming structure like BEM is helpful in avoiding unexptected styling issues.