<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sarah Dayan on Medium]]></title>
        <description><![CDATA[Stories by Sarah Dayan on Medium]]></description>
        <link>https://medium.com/@frontstuff?source=rss-20bd5f22250b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WuGf_fSHjEgr8o7BS1XUQA.jpeg</url>
            <title>Stories by Sarah Dayan on Medium</title>
            <link>https://medium.com/@frontstuff?source=rss-20bd5f22250b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 09:06:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@frontstuff/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[An introduction to test-driven development with Vue.js]]></title>
            <link>https://medium.com/free-code-camp/an-introduction-to-tdd-with-vue-js-66544710b50c?source=rss-20bd5f22250b------2</link>
            <guid isPermaLink="false">https://medium.com/p/66544710b50c</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Sarah Dayan]]></dc:creator>
            <pubDate>Fri, 17 May 2019 15:45:21 GMT</pubDate>
            <atom:updated>2019-05-17T15:45:21.856Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QphJEMJgj30s60_w" /><figcaption>Photo by <a href="https://unsplash.com/@_louisreed?utm_source=medium&amp;utm_medium=referral">Louis Reed</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Test-driven development (TDD) is a process where <strong>you write tests before you write the associated code</strong>. You first write a test that describes an expected behavior, and you run it, ensuring it fails. Then, you write the dumbest, most straightforward code you can to make the test pass. Finally, you refactor the code to make it right. And you repeat all the steps for each test until you’re done.</p><p>This approach has many advantages. First, <strong>it forces you to think before you code</strong>. It’s commonplace to rush into writing code before establishing what it should do. This practice leads to wasting time and writing complicated code. With TDD, any new piece of code requires a test first, so you have no choice but take the time to define what this code should do before you write it.</p><p>Secondly, <strong>it ensures you write unit tests</strong>. Starting with the code often leads to writing incomplete tests, or even no tests at all. Such a practice usually happens as a result of not having precise and exhaustive specs, which leads to spending more time coding than you should. Writing tests becomes a costly effort, which is easy to undermine once the production code is ready.</p><p><strong>Unit tests are critical to building robust code</strong>. Overlooking or rushing them increases chances of your code breaking in production at some point.</p><h3>Why do TDD for components?</h3><p><strong>Testing a component can be counter-intuitive</strong>. As we saw in <a href="https://frontstuff.io/unit-test-your-first-vuejs-component">Unit Test Your First Vue.js Component</a>, it requires a mental shift to wrap your head around testing components versus testing plain scripts, knowing what to test, and understanding the line between unit tests and end-to-end.</p><p><strong>TDD makes all this easier</strong>. Instead of writing tests by examining all bits and pieces of a finished project and trying to guess what you should cover, you’re doing the opposite. You’re starting from actual specs, a list of things that the component should <em>do</em>, without caring about how it does it. This way, you’re ensuring that all you test is the public API, but you’re also guaranteeing you don’t forget anything.</p><p>In this tutorial, we’ll build <strong>a color picker</strong>. For every swatch, users can access the matching color code, either in hexadecimal, RGB, or HSL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/0*45WZ3TNfXsL8EMCT.png" /><figcaption>Design inspired from <a href="https://dribbble.com/shots/2908891-Custom-Color-Picker-Exploration">Custom Color Picker Exploration</a> by <a href="https://dribbble.com/_ChrisCastillo">Chris Castillo</a></figcaption></figure><p>Despite its apparent simplicity, there are a bunch of small pieces of logic to test. They require some thinking before jumping into code.</p><p>In this article, we’ll deep dive into TDD. We’ll <a href="https://frontstuff.io/an-introduction-to-tdd-with-vuejs#write-down-your-specs">put some specs together</a> before we write a single line of code. Then, we’ll <a href="https://frontstuff.io/an-introduction-to-tdd-with-vuejs#write-test-driven-code">test every public feature</a> in a test-driven fashion. Finally, we’ll reflect on what we did and <a href="https://frontstuff.io/an-introduction-to-tdd-with-vuejs#afterthoughts">see what we can learn from it</a>.</p><h3>Before we start</h3><p>This tutorial assumes you’ve already built something with Vue.js before, and written unit tests for it using <a href="https://vue-test-utils.vuejs.org/">Vue Test Utils</a> and <a href="https://jestjs.io/">Jest</a> (or a similar test runner). It won’t go deeper into the fundamentals, so make sure you get up to speed first. If you’re not there yet, I recommend you go over <a href="https://frontstuff.io/build-your-first-vue-js-component">Build Your First Vue.js Component</a> and <a href="https://frontstuff.io/unit-test-your-first-vuejs-component">Unit Test Your First Vue.js Component</a>.</p><p><strong><em>TL;DR:</em></strong> <em>this post goes in-depth in the how and why. It’s designed to help you understand every decision behind testing a real-world Vue.js component with TDD and teach you how to make design decisions for your future projects. If you want to understand the whole thought process, read on. Otherwise, you can go directly to the </em><a href="https://frontstuff.io/an-introduction-to-tdd-with-vuejs#afterthoughts"><em>afterthoughts</em></a><em> at the end, or look at the final code on </em><a href="https://github.com/sarahdayan/colorpicker-tdd-tutorial"><em>GitHub</em></a><em>.</em></p><h3>Write down your specs</h3><p>Before you even write your first test, <strong>you should write down an overview of what the component should do</strong>. Having specs makes testing much more straightforward since you’re mostly rewriting each spec in the form of tests.</p><p>Let’s think about the different parts that compose our component, and what they should do.</p><p>First, we have a collection of <strong>color swatches</strong>. We want to be able to pass a list of custom colors and display as swatches in the component. The first one should be selected by default, and the end user can select a new one by clicking it.</p><p>Secondly, we have the <strong>color mode toggler</strong>. The end user should be able to switch between three modes: hexadecimal (default), RGB and HSL.</p><p>Finally, we have the <strong>color code output</strong>, where the end user can get the code for the currently selected color swatch. This code is a combination of the selected swatch and color mode. Thus, by default, it should display the first swatch as a hexadecimal value. When changing any of these, the code should update accordingly.</p><p>As you can see, we don’t go too deep into details; we don’t specify what the color mode labels should be, or what the active state looks like for the color swatches. We can make most of the small decisions on the fly, even when doing TDD. Yet, we’ve come <strong>from a simple definition of what the component should be, to a comprehensive set of specs to start from</strong>.</p><h3>Write test-driven code</h3><p>First, you need to create a new Vue project with <a href="https://cli.vuejs.org/">Vue CLI</a>. You can check <a href="https://frontstuff.io/build-your-first-vue-js-component">Build Your First Vue.js Component</a> if you need a step by step guide.</p><p>During the scaffolding process, manually select features and make sure you check <strong>Unit testing</strong>. Pick Jest as your testing solution, and proceed until the project is created, dependencies are installed, and you’re ready to go.</p><p>We’ll need to use SVG files as components, so you also need to install the right loader for them. Install <a href="https://www.npmjs.com/package/vue-svg-loader">vue-svg-loader</a> as a dev dependency, and add a rule for it in your vue.config.js file.</p><pre>// vue.config.js</pre><pre>module.exports = {<br>  chainWebpack: config =&gt; {<br>    const svgRule = config.module.rule(&#39;svg&#39;)<br>    svgRule.uses.clear()<br>    svgRule.use(&#39;vue-svg-loader&#39;).loader(&#39;vue-svg-loader&#39;)<br>  }<br>}</pre><p>This loader doesn’t play well with Jest by default, which causes tests to throw. To fix it, create a svgTransform.js file <a href="https://vue-svg-loader.js.org/faq.html#how-to-use-this-loader-with-jest">as documented on the website</a>, and edit your jest.config.js as follows:</p><pre>// svgTransform.js</pre><pre>const vueJest = require(&#39;vue-jest/lib/template-compiler&#39;)</pre><pre>module.exports = {<br>  process(content) {<br>    const { render } = vueJest({<br>      content,<br>      attrs: {<br>        functional: false<br>      }<br>    })</pre><pre>    return `module.exports = { render: ${render} }`<br>  }<br>}</pre><pre>// jest.config.js</pre><pre>module.exports = {<br>  // ...<br>  transform: {<br>    // ...<br>    &#39;.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$&#39;: &#39;jest-transform-stub&#39;,<br>    &#39;^.+\\.svg$&#39;: &#39;&lt;rootDir&gt;/svgTransform.js&#39;<br>  },<br>  // ...<br>}</pre><p>Note that we’ve removed “svg” from the first regular expression (the one that gets transformed with jest-transform-stub). This way, we ensure SVGs get picked up by svgTransform.js.</p><p>Additionally, you need to install <a href="https://www.npmjs.com/package/color-convert">color-convert</a> as a dependency. We’ll need it both in our code and in our tests later on.</p><p><strong>Don’t serve the project yet</strong>. We’re going to write tests and rely on them passing or not to move on. We don’t want to control whether what we build works by testing it visually in the browser, nor being distracted by how it looks.</p><p>Instead, open your project and create a new ColorPicker.vue single-file component in the src/components/ directory. In tests/unit/, create its associated spec file.</p><pre>&lt;!-- ColorPicker.vue --&gt;</pre><pre>&lt;template&gt;<br>  &lt;div&gt;&lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;script&gt;<br>export default {}<br>&lt;/script&gt;</pre><pre>&lt;style&gt;<br>&lt;/style&gt;</pre><pre>// ColorPicker.spec.js</pre><pre>import { shallowMount } from &#39;@vue/test-utils&#39;<br>import ColorPicker from &#39;@/components/ColorPicker&#39;</pre><pre>describe(&#39;ColorPicker&#39;, () =&gt; {<br>  // let&#39;s do this!<br>})</pre><p>In your terminal, execute the following command to run tests:</p><pre>npm run test:unit --watchAll</pre><p>For now, you should get an error because you don’t yet have tests. Don’t worry though; we’ll fix this shortly 🙂 Note the usage of the --watchAll flag in the command: Jest is now watching your files. This way, you won’t have to re-run test by hand.</p><p>TDD goes in 3 stages:</p><ol><li><strong>Red</strong>: you write a test that describes an expected behavior, then you run it, ensuring it fails.</li><li><strong>Green</strong>: you write the dumbest, most straightforward code you can to make the test pass.</li><li><strong>Refactor</strong>: you refactor the code to make it right.</li></ol><h3>Step 1: Red</h3><p>Time to write our first test! We’ll start with the color swatches. For clarity, we’ll wrap all tests for each distinct element in their own suite, using a describe block.</p><p>First, we want to make sure that the component displays each color that we provide as an individual swatch. We would pass those as props, in the form of an array of hexadecimal strings. In the component, we would display the list as an unordered list, and assign the background color via a style attribute.</p><pre>import { shallowMount } from &#39;@vue/test-utils&#39;<br>import ColorPicker from &#39;@/components/ColorPicker&#39;<br>import convert from &#39;color-convert&#39;</pre><pre>let wrapper = null</pre><pre>const propsData = {<br>  swatches: [&#39;e3342f&#39;, &#39;3490dc&#39;, &#39;f6993f&#39;, &#39;38c172&#39;, &#39;fff&#39;]<br>}</pre><pre>beforeEach(() =&gt; (wrapper = shallowMount(ColorPicker, { propsData })))<br>afterEach(() =&gt; wrapper.destroy())</pre><pre>describe(&#39;ColorPicker&#39;, () =&gt; {<br>  describe(&#39;Swatches&#39;, () =&gt; {<br>    test(&#39;displays each color as an individual swatch&#39;, () =&gt; {<br>      const swatches = wrapper.findAll(&#39;.swatch&#39;)<br>      propsData.swatches.forEach((swatch, index) =&gt; {<br>        expect(swatches.at(index).attributes().style).toBe(<br>          `background: rgb(${convert.hex.rgb(swatch).join(&#39;, &#39;)})`<br>        )<br>      })<br>    })<br>  })<br>})</pre><p>We mounted our ColorPicker component and wrote a test that expects to find items with a background color matching the colors passed as props. <strong>This test is bound to fail</strong>: we currently have nothing in ColorPicker.vue. If you look at your terminal, you should have an error saying that no item exists at 0. This is great! <strong>We just passed the first step of TDD with flying colors.</strong></p><h3>Step 2: Green</h3><p>Our test is failing; we’re on the right track. Now, time to make it pass. We’re not much interested in writing working or smart code at this point, all we want is to make Jest happy. Right now, Vue Test Utils complains about the fact that we don’t event have no item at index 0.</p><pre>[vue-test-utils]: no item exists at 0</pre><p>The simplest thing we can do to make that error go away is to add an unordered list with a swatch class on the list item.</p><pre>&lt;template&gt;<br>  &lt;div class=&quot;color-picker&quot;&gt;<br>    &lt;ul class=&quot;swatches&quot;&gt;<br>      &lt;li class=&quot;swatch&quot;&gt;&lt;/li&gt;<br>    &lt;/ul&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><p>Jest still complains but the error has changed:</p><pre>Expected value to equal:<br>  &quot;background: rgb(227, 52, 47);&quot;<br>Received:<br>  undefined</pre><p>This makes sense; the list item doesn’t have a style attribute. The simplest thing we can do about it is to hardcode the style attribute. This isn’t what we want in the end, but, we aren’t concerned about it yet. What we want is <strong>for our test to go green</strong>.</p><p>We can therefore hardcode five list items with the expected style attributes:</p><pre>&lt;ul class=&quot;swatches&quot;&gt;<br>  &lt;li class=&quot;swatch&quot; style=&quot;background: rgb(227, 52, 47);&quot;&gt;&lt;/li&gt;<br>  &lt;li class=&quot;swatch&quot; style=&quot;background: rgb(52, 144, 220);&quot;&gt;&lt;/li&gt;<br>  &lt;li class=&quot;swatch&quot; style=&quot;background: rgb(246, 153, 63);&quot;&gt;&lt;/li&gt;<br>  &lt;li class=&quot;swatch&quot; style=&quot;background: rgb(56, 193, 114);&quot;&gt;&lt;/li&gt;<br>  &lt;li class=&quot;swatch&quot; style=&quot;background: rgb(255, 255, 255);&quot;&gt;&lt;/li&gt;<br>&lt;/ul&gt;</pre><p>The test should now pass.</p><h3>Step 3: Refactor</h3><p>At this stage, we want to rearrange our code to make it right, without breaking tests. In our case, we don’t want to keep the list items and their style attributes hardcoded. Instead, it would be better to receive swatches as a prop, iterate over them to generate the list items, and assign the colors as their background.</p><pre>&lt;template&gt;<br>  &lt;div class=&quot;color-picker&quot;&gt;<br>    &lt;ul class=&quot;swatches&quot;&gt;<br>      &lt;li<br>        :key=&quot;index&quot;<br>        v-for=&quot;(swatch, index) in swatches&quot;<br>        :style=&quot;{ background: `#${swatch}` }&quot;<br>        class=&quot;swatch&quot;<br>      &gt;&lt;/li&gt;<br>    &lt;/ul&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;script&gt;<br>export default {<br>  props: {<br>    swatches: {<br>      type: Array,<br>      default() {<br>        return []<br>      }<br>    }<br>  }<br>}<br>&lt;/script&gt;</pre><p>When tests re-run, they should still pass 🥳 This means <strong>we’ve successfully refactored the code without affecting the output</strong>. Congratulations, you’ve just completed your first TDD cycle!</p><p>Now, before we go to the next test, let’s reflect a bit. You may be wondering:</p><blockquote>“Isn’t this a bit dumb? I knew the test would fail. Am I not wasting time by running it anyway, then hardcoding the right value, see the test pass, then make the code right? Can’t I go to the refactor step directly?”</blockquote><p>It’s understandable that you’re feeling confused by the process. Yet, try to look at things from a different angle: the point here isn’t to <em>prove</em> that the test doesn’t pass. We know it won’t. What we want to look at is what our test <em>expects</em>, make them happy in the simplest possible way, and finally write smarter code without breaking anything.</p><p>That’s the whole idea of test-driven development: we don’t write code to make things work, <strong>we write code to make tests pass</strong>. By reversing the relationship, we’re ensuring robust tests with a focus on the outcome.</p><h3>What are we testing?</h3><p>Another question that may come to mind is <strong>how we’re deciding what to test</strong>. In <a href="https://frontstuff.io/unit-test-your-first-vuejs-component">Unit Test Your First Vue.js Component</a>, we saw that we should only be testing the public API of our component, not the internal implementation. Strictly speaking, this means we should cover <strong>user interactions</strong> and <strong>props changes</strong>.</p><p>But is that all? For example, is it okay for the output HTML to break? Or for CSS class names to change? Are we sure nobody is relying on them? That you aren’t yourself?</p><p><strong>Tests should give you confidence that you aren’t shipping broken software.</strong> What people can do with your program shouldn’t stop working the way they expect it to work. It can mean different things depending on the project and use case.</p><p>For example, if you’re building this color panel as an open source component, your users are other developers who use it in their own projects. They’re likely relying on the class names you provide to style the component to their liking. <strong>The class names become a part of your public API because your users rely on them.</strong></p><p>In our case, we may not necessarily be making an open source component, but we have view logic that depends on specific class names. For instance, it’s important for active swatches to have an active class name, because we’ll rely on it to display a checkmark, in CSS. If someone changes this by accident, we want to know about it.</p><p>Testing scenarios for UI components highly depend on the use case and expectations. Whichever the case, what you need to ask yourself is <strong>do I care about this if it changes</strong>?</p><h3>Next tests</h3><h4>Testing the swatches</h4><p>Let’s move on to the next test. We expect the first swatch of the list to be the one that’s selected by default. From the outside, <strong>this is something that we want to ensure keeps on working the same way</strong>. Users could, for instance, rely on the active class name to style the component.</p><pre>test(&#39;sets the first swatch as the selected one by default&#39;, () =&gt; {<br>  const firstSwatch = wrapper.find(&#39;.swatch&#39;)<br>  expect(firstSwatch.classes()).toContain(&#39;active&#39;)<br>})</pre><p>This test, too, should fail, as list items currently don’t have any classes. We can easily make this pass by adding the class on the first list item.</p><pre>&lt;li<br>  :key=&quot;index&quot;<br>  v-for=&quot;(swatch, index) in swatches&quot;<br>  :style=&quot;{ background: `#${swatch}` }&quot;<br>  class=&quot;swatch&quot;<br>  :class=&quot;{ &#39;active&#39;: index === 0 }&quot;<br>&gt;&lt;/li&gt;</pre><p>The test now passes; however, we’ve hardcoded the logic into the template. We can refactor that by externalizing the index onto which the class applies. This way, we can change it later.</p><pre>&lt;template&gt;<br>  &lt;!-- ... --&gt;<br>  &lt;li<br>    :key=&quot;index&quot;<br>    v-for=&quot;(swatch, index) in swatches&quot;<br>    :style=&quot;{ background: `#${swatch}` }&quot;<br>    class=&quot;swatch&quot;<br>    :class=&quot;{ active: index === activeSwatch }&quot;<br>  &gt;&lt;/li&gt;<br>  &lt;!-- ... --&gt;<br>&lt;/template&gt;</pre><pre>export default {<br>  // ...<br>  data() {<br>    return {<br>      activeSwatch: 0<br>    }<br>  }<br>}</pre><p>This naturally leads us to our third test. We want to change the active swatch whenever the end user clicks it.</p><pre>test(&#39;makes the swatch active when clicked&#39;, () =&gt; {<br>  const targetSwatch = wrapper.findAll(&#39;.swatch&#39;).at(2)<br>  targetSwatch.trigger(&#39;click&#39;)<br>  expect(targetSwatch.classes()).toContain(&#39;active&#39;)<br>})</pre><p>For now, nothing happens when we click a swatch. However, thanks to our previous refactor, we can make this test go green and even skip the refactor step.</p><pre>&lt;li<br>  :key=&quot;index&quot;<br>  v-for=&quot;(swatch, index) in swatches&quot;<br>  :style=&quot;{ background: `#${swatch}` }&quot;<br>  class=&quot;swatch&quot;<br>  :class=&quot;{ active: index === activeSwatch }&quot;<br>  @click=&quot;activeSwatch = index&quot;<br>&gt;&lt;/li&gt;</pre><p>This code makes the test pass and doesn’t even need a refactor. <strong>This is a fortunate side-effect of doing TDD</strong>: sometimes, the process leads to either writing new tests that either don’t need refactors, or even that pass right away.</p><p>Active swatches should show a checkmark. We’ll add it now <strong>without writing a test</strong>: instead, we’ll control their visibility via CSS later. This is alright since we’ve already tested how the active class applies.</p><p>First, create a checkmark.svg file in src/assets/.</p><pre>&lt;svg viewBox=&quot;0 0 448.8 448.8&quot;&gt;<br>  &lt;polygon points=&quot;142.8 323.9 35.7 216.8 0 252.5 142.8 395.3 448.8 89.3 413.1 53.6&quot;/&gt;<br>&lt;/svg&gt;</pre><p>Then, import it in the component.</p><pre>import CheckIcon from &#39;@/assets/check.svg&#39;</pre><pre>export default {<br>  // ...<br>  components: { CheckIcon }<br>}</pre><p>Finally, add it inside the list items.</p><pre>&lt;li ... &gt;<br>  &lt;check-icon /&gt;<br>&lt;/li&gt;</pre><p>Good! We can now move on to the next element of our component: <strong>the color mode</strong>.</p><h4>Testing the color mode</h4><p>Let’s now implement the color mode toggler. The end user should be able to switch between hexadecimal, RGB and HSL. We’re defining these modes internally, but we want to ensure they render correctly.</p><p>Instead of testing button labels, <strong>we’ll rely on class names</strong>. It makes our test more robust, as we can easily define a class name as part of our component’s contract. However, button labels should be able to change.</p><p>Now you may be tempted to check for these three specific modes, but that would make the test brittle. What if we change them? What if we add one, or remove one? That would still be the same logic, yet the test would fail, forcing us to go and edit it.</p><p>One solution could be to access the component’s data to iterate on the modes dynamically. Vue Test Utils lets us do that through the <a href="https://vue-test-utils.vuejs.org/api/wrapper/#properties">vm</a> property, but again, this tightly couples our test with the internal implementation of the modes. If tomorrow, we decided to change the way we define modes, the test would break.</p><p>Another solution is to keep going with black box testing and only expect the class name to match a given <em>pattern</em>. We don’t care that it’s color-mode-hex, color-mode-hsl or color-mode-xyz, as long as it looks like what we expect from the outside. Jest lets us do that with regular expression matchers.</p><pre>// ...<br>describe(&#39;Color model&#39;, () =&gt; {<br>  test(&#39;displays each mode as an individual button&#39;, () =&gt; {<br>    const buttons = wrapper.findAll(&#39;.color-mode&#39;)<br>    buttons.wrappers.forEach(button =&gt; {<br>      expect(button.classes()).toEqual(<br>        expect.arrayContaining([expect.stringMatching(/color-mode-\w{1,}/)])<br>      )<br>    })<br>  })<br>})</pre><p>Here, we’re expecting elements with a class that follows the pattern “color-mode-“ + any word character (in ECMAScript, any character within [a-zA-Z_0-9]). We could add or remove any mode we want, and the test would still be valid.</p><p>Naturally, right now, the test should fail, as there are no buttons with class color-mode yet. We can make it pass by hardcoding them in the component.</p><pre>&lt;div class=&quot;color-modes&quot;&gt;<br>  &lt;button class=&quot;color-mode color-mode-hex&quot;&gt;&lt;/button&gt;<br>  &lt;button class=&quot;color-mode color-mode-rgb&quot;&gt;&lt;/button&gt;<br>  &lt;button class=&quot;color-mode color-mode-hsl&quot;&gt;&lt;/button&gt;<br>&lt;/div&gt;</pre><p>We can now refactor this code by adding the modes as private data in our component and iterate over them.</p><pre>&lt;template&gt;<br>  &lt;!-- ... --&gt;<br>  &lt;div class=&quot;color-modes&quot;&gt;<br>    &lt;button<br>      :key=&quot;index&quot;<br>      v-for=&quot;(mode, index) in colorModes&quot;<br>      class=&quot;color-mode&quot;<br>      :class=&quot;`color-mode-${mode}`&quot;<br>    &gt;{{ mode }}&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;!-- ... --&gt;<br>&lt;/template&gt;</pre><pre>export default {<br>  // ...<br>  data() {<br>    return {<br>      activeSwatch: 0,<br>      colorModes: [&#39;hex&#39;, &#39;rgb&#39;, &#39;hsl&#39;]<br>    }<br>  }<br>}</pre><p>Good! Let’s move on.</p><p>As with the swatches, we want the first mode to be set as active. We can copy the test we wrote and adapt it to this new use case.</p><pre>test(&#39;sets the first mode as the selected one by default&#39;, () =&gt; {<br>  const firstButton = wrapper.find(&#39;.color-mode&#39;)<br>  expect(firstButton.classes()).toContain(&#39;active&#39;)<br>})</pre><p>We can make this test pass by manually adding the class on the first list item.</p><pre>&lt;button<br>  :key=&quot;index&quot;<br>  v-for=&quot;(mode, index) in colorModes&quot;<br>  class=&quot;color-mode&quot;<br>  :class=&quot;[{ active: index === 0 }, `color-mode-${mode}`]&quot;<br>&gt;{{ mode }}&lt;/button&gt;</pre><p>Finally, we can refactor by externalizing the index onto which the class applies.</p><pre>&lt;template&gt;<br>  &lt;!-- ... --&gt;<br>  &lt;button<br>    :key=&quot;index&quot;<br>    v-for=&quot;(mode, index) in colorModes&quot;<br>    class=&quot;color-mode&quot;<br>    :class=&quot;[{ active: index === activeMode }, `color-mode-${mode}`]&quot;<br>  &gt;{{ mode }}&lt;/button&gt;<br>  &lt;!-- ... --&gt;<br>&lt;/template&gt;</pre><pre>export default {<br>  // ...<br>  data() {<br>    return {<br>      activeSwatch: 0,<br>      activeMode: 0,<br>      colorModes: [&#39;hex&#39;, &#39;rgb&#39;, &#39;hsl&#39;]<br>    }<br>  }<br>}</pre><p>We need to change the active mode whenever the end user clicks the associated button, as with the swatches.</p><pre>test(&#39;sets the color mode button as active when clicked&#39;, () =&gt; {<br>  const targetButton = wrapper.findAll(&#39;.color-mode&#39;).at(2)<br>  targetButton.trigger(&#39;click&#39;)<br>  expect(targetButton.classes()).toContain(&#39;active&#39;)<br>})</pre><p>We can now add a @click directive as we did with the swatches, and make the test go green without having to refactor.</p><pre>&lt;button<br>  :key=&quot;index&quot;<br>  v-for=&quot;(mode, index) in colorModes&quot;<br>  class=&quot;color-mode&quot;<br>  :class=&quot;[{ active: index === activeMode }, `color-mode-${mode}`]&quot;<br>  @click=&quot;activeMode = index&quot;<br>&gt;{{ mode }}&lt;/button&gt;</pre><h4>Testing the color code</h4><p>Now that we’re done testing the swatches and color code, we can move on to the third and final element of our color picker: <strong>the color code</strong>. What we display in there is a combination of the other two: the selected swatch defines the color we should display, and the selected mode determines how to display it.</p><p>First, we want to make sure we initially display the default swatch in the default mode. We have the information to build this since we’ve implemented the swatches and the color mode.</p><p>Let’s start with a (failing) test.</p><pre>describe(&#39;Color code&#39;, () =&gt; {<br>  test(&#39;displays the default swatch in the default mode&#39;, () =&gt; {<br>    expect(wrapper.find(&#39;.color-code&#39;).text()).toEqual(&#39;#e3342f&#39;)<br>  })<br>})</pre><p>Now, let’s make this pass by hardcoding the expected result in the component.</p><pre>&lt;div class=&quot;color-code&quot;&gt;#e3342f&lt;/div&gt;</pre><p>Good! Time to refactor. We have a raw color in hexadecimal mode, and we’re willing to output it in hexadecimal format. The only difference between our input and output values is that we want to prepend the latter with a hash character. The easiest way of doing so with Vue is via a computed property.</p><pre>&lt;template&gt;<br>  &lt;!-- ... --&gt;<br>  &lt;div class=&quot;color-code&quot;&gt;{{ activeCode }}&lt;/div&gt;<br>  &lt;!-- ... --&gt;<br>&lt;/template&gt;</pre><pre>export default {<br>  // ...<br>  computed: {<br>    activeCode() {<br>      return `#${this.swatches[this.activeSwatch]}`<br>    }<br>  }<br>}</pre><p>This should keep the test green. However, there’s an issue with this computed property: it only works for hexadecimal values. It should keep on working when we change the color, but not when we change the mode. We can verify this with another test.</p><pre>test(&#39;displays the code in the right mode when changing mode&#39;, () =&gt; {<br>  wrapper.find(&#39;.color-mode-hsl&#39;).trigger(&#39;click&#39;)<br>  expect(wrapper.find(&#39;.color-code&#39;).text()).toEqual(&#39;2°, 76%, 54%&#39;)<br>})</pre><p>Here, we’ve changed to HSL mode, but we’re still getting the hexadecimal output. We need to refactor our code so that our activeCode computed property is not only aware of the current color, but also the current color mode. One way we can achieve this is to create computed properties for each mode and proxy them through activeCode based on the selected mode.</p><p>First, we should simplify access to the current color and mode. Right now, we need to do an array lookup, which is repetitive and makes the code hard to read. We can use computed properties to wrap that logic.</p><pre>export default {<br>  // ...<br>  computed: {<br>    // ...<br>    activeColorValue() {<br>      return this.swatches[this.activeSwatch]<br>    },<br>    activeModeValue() {<br>      return this.colorModes[this.activeMode]<br>    }<br>  }<br>}</pre><p>As you can see, we’re not writing tests for these computed properties, as they aren’t part of our public API. We’ll use them later in our dedicated color mode computed properties, which themselves will be proxied in activeCode, which we’re testing in our “Color code” suite. <strong>All we care about is that the color code renders as expected</strong> so that the user can rely on them. How we get there are implementation details that we need to be able to change if need be.</p><p>We can now write our dedicated computed properties for each mode. We’ll map their name onto the ones in colorModes, so we can do an array lookup later in activeCode to return the right one.</p><p>For the hexadecimal output, we can externalize what we currently have in activeCode and refactor it using activeColorValue.</p><pre>export default {<br>  // ...<br>  computed: {<br>    // ...<br>    hex() {<br>      return `#${this.activeColorValue}`<br>    }<br>  }<br>}</pre><p>Now, let’s modify activeCode so it proxies the right computed property depending on the active mode.</p><pre>export default {<br>  // ...<br>  computed: {<br>    // ...<br>    activeCode() {<br>      return this[this.activeModeValue]<br>    }<br>  }<br>}</pre><p>This still shouldn’t make our latest test pass, since we haven’t written a computed property for it. However, our test that checks if the default mode renders correctly is still passing, which is a good sign we’re on the right track.</p><p>We now want to write a computed property that returns the color output in HSL mode. For this, we’ll use color-convert, an npm package that lets us convert colors in many different modes. We’ve already been using it in our tests, so we don’t have to reinstall it.</p><pre>import convert from &#39;color-convert&#39;</pre><pre>export default {<br>  // ...<br>  computed: {<br>    // ...<br>    hsl() {<br>      const hslColor = convert.hex.hsl(this.activeColorValue)<br>      return `${hslColor[0]}°, ${hslColor[1]}%, ${hslColor[2]}%`<br>    }<br>  }<br>}</pre><p>Great, our test passes! We can now finish this up adding the missing RGB mode.</p><p>Yet, as you can see, we’re currently not testing the output of our color computed properties in isolation, but through other tests. To make things cleaner, we could decouple that logic from the component, import it as a dependency, and test it separately. This has several benefits:</p><ul><li>it keeps the component from growing every time we want to add a color mode,</li><li>it keeps domains separated: the component focuses on its own view logic, and the color modes utility takes care of testing each mode exhaustively.</li></ul><p>First, create a new color.js file in the src/utils/ directory, and a matching spec file in tests/unit/.</p><pre>// color.spec.js</pre><pre>import { rgb, hex, hsl } from &#39;@/utils/color&#39;</pre><pre>// color.js</pre><pre>import convert from &#39;color-convert&#39;</pre><pre>export const rgb = () =&gt; {}</pre><pre>export const hex = () =&gt; {}</pre><pre>export const hsl = () =&gt; {}</pre><p>We can use TDD to test those three functions and make sure they always return the expected value. We can extract the logic we had in our Vue component for the last two, and write the RGB function from scratch.</p><p>For the sake of brevity, we’ll cover all three tests at once, but the process remains the same.</p><pre>import { rgb, hex, hsl } from &#39;@/utils/color&#39;</pre><pre>const color = &#39;e3342f&#39;</pre><pre>describe(&#39;color&#39;, () =&gt; {<br>  test(&#39;returns the color into RGB notation&#39;, () =&gt; {<br>    expect(rgb(color)).toBe(&#39;227, 52, 47&#39;)<br>  })<br>  test(&#39;returns the color into hexadecimal notation&#39;, () =&gt; {<br>    expect(hex(color)).toBe(&#39;#e3342f&#39;)<br>  })<br>  test(&#39;returns the color into HSL notation&#39;, () =&gt; {<br>    expect(hsl(color)).toBe(&#39;2°, 76%, 54%&#39;)<br>  })<br>})</pre><p>We now have three failing tests. The first thing we can do is to return hardcoded values to go green.</p><pre>export const rgb = () =&gt; &#39;227, 52, 47&#39;</pre><pre>export const hex = () =&gt; &#39;#e3342f&#39;</pre><pre>export const hsl = () =&gt; &#39;2°, 76%, 54%&#39;</pre><p>Now, we can start refactoring by migrating the code from our Vue component.</p><pre>export const hex = () =&gt; `#${color}`</pre><pre>export const hsl = color =&gt; {<br>  const hslColor = convert.hex.hsl(color)<br>  return `${hslColor[0]}°, ${hslColor[1]}%, ${hslColor[2]}%`<br>}</pre><p>Finally, we can implement our rgb function.</p><pre>export const rgb = color =&gt; convert.hex.rgb(color).join(&#39;, &#39;)</pre><p>All tests should stay green!</p><p>We can now use the color utilities in our Vue component and refactor it a bit. We no longer need to import color-convert in the component, nor do we need dedicated computed properties for each mode, or even for getting the active color and mode values. All we need to keep is activeCode, where we can store all the necessary logic.</p><p>This is a good example where doing black box testing helps us: we’ve been focusing on testing the public API; thus <strong>we can refactor the internals of our component without breaking the tests</strong>. Removing properties like activeColorValue or hex doesn’t matter, because we were never testing them directly.</p><pre>// ...<br>import { rgb, hex, hsl } from &#39;@/utils/color&#39;</pre><pre>const modes = { rgb, hex, hsl }</pre><pre>export default {<br>  // ...<br>  computed: {<br>    activeCode() {<br>      const activeColor = this.swatches[this.activeSwatch]<br>      const activeMode = this.colorModes[this.activeMode]<br>      return modes[activeMode](activeColor)<br>    }<br>  }<br>}</pre><p>We now have much terser code in our component, and better domain separation, while still respecting the component’s contract.</p><p>Finally, we can implement a missing test: the one that ensures the color code changes whenever we click a new swatch. This should already go green, but it’s still essential for us to write it, so we can know about it if it breaks.</p><pre>test(&#39;displays the code in the right color when changing color&#39;, () =&gt; {<br>  wrapper<br>    .findAll(&#39;.swatch&#39;)<br>    .at(2)<br>    .trigger(&#39;click&#39;)<br>  expect(wrapper.find(&#39;.color-code&#39;).text()).toEqual(&#39;#f6993f&#39;)<br>})</pre><p>And we’re done! We just built a fully functional Vue component using TDD, without relying on browser output, <strong>and our tests are ready</strong>.</p><h3>Visual control</h3><p>Now that our component is ready, we can see how it looks and play with it in the browser. This allows us to add the CSS and ensure we didn’t miss out on anything.</p><p>First, mount the component into the main App.vue file.</p><pre>&lt;!-- App.vue --&gt;</pre><pre>&lt;template&gt;<br>  &lt;div id=&quot;app&quot;&gt;<br>    &lt;color-picker :swatches=&quot;[&#39;e3342f&#39;, &#39;3490dc&#39;, &#39;f6993f&#39;, &#39;38c172&#39;, &#39;fff&#39;]&quot;/&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;script&gt;<br>import ColorPicker from &#39;@/components/ColorPicker&#39;</pre><pre>export default {<br>  name: &#39;app&#39;,<br>  components: {<br>    ColorPicker<br>  }<br>}<br>&lt;/script&gt;</pre><p>Then, run the app by executing the following script, and open it in your browser at <a href="http://localhost:8080/">http://localhost:8080/</a>.</p><pre>npm run serve</pre><p>You should see your color picker! It doesn’t look like much for now, but it works. Try clicking colors and change the color mode; you should see the color code change.</p><p>To see the component with proper styling, add the following CSS between the style tags:</p><pre>.color-picker {<br>  background-color: #fff;<br>  border: 1px solid #dae4e9;<br>  border-radius: 0.125rem;<br>  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);<br>  color: #596a73;<br>  font-family: BlinkMacSystemFont, Helvetica Neue, sans-serif;<br>  padding: 1rem;<br>}</pre><pre>.swatches {<br>  color: #fff;<br>  display: flex;<br>  flex-wrap: wrap;<br>  list-style: none;<br>  margin: -0.25rem -0.25rem 0.75rem;<br>  padding: 0;<br>}</pre><pre>.swatch {<br>  border-radius: 0.125rem;<br>  cursor: pointer;<br>  height: 2rem;<br>  margin: 0.25rem;<br>  position: relative;<br>  width: 2rem;<br>}</pre><pre>.swatch::after {<br>  border-radius: 0.125rem;<br>  bottom: 0;<br>  box-shadow: inset 0 0 0 1px #dae4e9;<br>  content: &#39;&#39;;<br>  display: block;<br>  left: 0;<br>  mix-blend-mode: multiply;<br>  position: absolute;<br>  right: 0;<br>  top: 0;<br>}</pre><pre>.swatch svg {<br>  display: none;<br>  color: #fff;<br>  fill: currentColor;<br>  margin: 0.5rem;<br>}</pre><pre>.swatch.active svg {<br>  display: block;<br>}</pre><pre>.color-modes {<br>  display: flex;<br>  font-size: 1rem;<br>  letter-spacing: 0.05rem;<br>  margin: 0 -0.25rem 0.75rem;<br>}</pre><pre>.color-mode {<br>  background: none;<br>  border: none;<br>  color: #9babb4;<br>  cursor: pointer;<br>  display: block;<br>  font-weight: 700;<br>  margin: 0 0.25rem;<br>  padding: 0;<br>  text-transform: uppercase;<br>}</pre><pre>.color-mode.active {<br>  color: #364349;<br>}</pre><pre>.color-code {<br>  border: 1px solid #dae4e9;<br>  border-radius: 0.125rem;<br>  color: #364349;<br>  text-transform: uppercase;<br>  padding: 0.75rem;<br>}</pre><p>You should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*e2w8W0MplRF7UPdc.gif" /></figure><p>And we’re done!</p><h3>Afterthoughts</h3><h4>How can we improve this?</h4><p>For now, we have a robust test suite. Even though we don’t have 100% coverage, we can feel confident with our component going out in the wild, and evolving over time. There are still a couple of things we could improve though, depending on the use case.</p><p>First, you may notice that when clicking the white swatch, the checkmark doesn’t show up. That’s not a bug, rather a visual issue: the checkmark is there, but we can’t see it because it’s white on white. You could add a bit of logic to fix this: when a color is lighter than a certain threshold (let’s say 90%), you could add a light class on the swatch. This would then let you apply some specific CSS and make the checkmark dark.</p><p>Fortunately, you already have all you need: the color-converter package can help you determine whether a color is light (with the HSL utilities), and you already have a color utility module to store that logic and test it in isolation. To see what the finished code could look like, check out the project’s repository on <a href="https://github.com/sarahdayan/colorpicker-tdd-tutorial">GitHub</a>.</p><p>We could also reinforce the suite by adding a few tests to make sure some expected classes are there. This doesn’t test actual logic, but would still be particularly useful if someone was relying on those class names to style the component from the outside. Again, everything depends on your use case: test what shouldn’t change without you knowing, don’t only add tests for the sake of it.</p><h4>What did we learn?</h4><p>There are several lessons to learn from this TDD experiment. It brings a lot to the table but also highlights a few challenges that we should be aware of.</p><p>First, TDD is a <strong>fantastic way to write robust tests</strong>, not too many and not too few. Have you ever finished a component, moved on to tests and thought <em>“where do I even start?”</em>? Looking at finished code and figuring out what to test is hard. It’s tempting to get it done quickly, overlook some critical parts and end up with an incomplete test suite. Or you can adopt a defensive approach and test everything, risking to focus on implementation details and writing brittle tests.</p><p>Adopting TDD for developing UI components helps us focus on exactly what to test by <strong>defining, before writing any line of code, if this is part of the contract or not</strong>.</p><p>Secondly, <strong>TDD encourages refactors, leading to better software design</strong>. When you’re writing tests after coding, you’re usually no longer in a refactoring dynamic. You can fix your code if you find issues while testing, but at this stage, you’re most likely done with the implementation. <strong>This separation between writing code and writing test is where lies the issue.</strong></p><p>With TDD, <strong>you’re creating a deeper connection between code and tests, with a strong focus on making the public API reliable</strong>. Implementation comes right after you’ve guaranteed the outcome. This is why the <em>green</em> step is critical: you first need your test to pass, then ensure it never breaks. Instead of implementing your way to a working solution, you’re reversing the relationship, focusing on the contract first, and allowing the implementation to remain disposable. Because refactoring comes last, and you’ve established the contract, you now have mental space to make things right, clean some code, adopt a better design, or focus on performance.</p><p>It’s worth noting that <strong>TDD is much easier to follow with specs</strong>. When you already have a clear overview of everything the component should do, you can translate those specifications into tests. Some teams use frameworks like <a href="https://en.wikipedia.org/wiki/Acceptance_test%E2%80%93driven_development">ATDD</a> (acceptance test–driven development), where the involved parties develop specifications from a business perspective. The final specs, or acceptance tests, are a perfect base to write tests following TDD.</p><p>On the other hand, going with TDD to test UI components can be difficult at first, and require some prior knowledge before diving into it. For starters, <strong>you need to have good knowledge of your testing libraries</strong> so that you can write reliable assertions. Look at the test we wrote with a regular expression: the syntax is not the most straightforward. If you don’t know the library well, it’s easy to write a test that fails for the wrong reasons, which would end up hindering the whole TDD process.</p><p>Similarly, you need to be aware of some details regarding the values you expect; otherwise, you could end up battling with your tests and doing some annoying back-and-forths. On that matter, UI components are more challenging than renderless libraries, because of the various ways the DOM specifications can be implemented.</p><p>Take the first test of our suite for example: we’re testing background colors. However, even though we’re passing hexadecimal colors, we’re expecting RGB return values. That’s because Jest uses <a href="https://github.com/jsdom/jsdom">jsdom</a>, a Node.js implementation of the DOM and HTML standards. If we were running our tests in a specific browser, we might have a different return value. This can be tricky when you’re testing different engines. You may have to seek some more advanced conversion utilities or use environment variables to handle the various implementations.</p><h4>Is it worth it?</h4><p>If you made it this far, you’ve probably realized that <strong>TDD demands time</strong>. This article itself is over 6,000 words! This can be a bit scary if you’re used to faster development cycles, and probably looks impossible if you’re often working under pressure. However, it’s important to bust the myth that TDD would somehow double development time for little return on investment, because this is entirely false.</p><p>TDD requires some practice, and you’ll get faster over time. What feels clumsy today can become a second nature tomorrow, if you do it regularly. I encourage you not to discard something because it’s new and feels awkward: give it some time to assess it fairly, then take a decision.</p><p>Secondly, <strong>time spent on writing test-driven code is time you won’t spend fixing bugs</strong>.</p><p>Fixing bugs is far more costly than preventing them. If you’ve ever had to fix critical production bugs, you know this feels close to holding an open wound on a surgical patient with one hand, while trying to operate with the other one. In the desert. At night. With a Swiss Army knife. It’s messy, stressful, suboptimal, and bears high chances of screwing up something else in the process. If you want to preserve your sanity and the trust your end users have in your software, <strong>you want to avoid those situations at all costs</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*-ypCMc0eow3xfIdm.gif" /></figure><p>Tests help you catch bugs before they make it to production, and TDD helps you write better tests. <strong>If you think you should test your software, then you should care about making these tests useful in the first place.</strong> Otherwise, the whole thing is only a waste of time.</p><p>As with anything, I encourage you to try TDD before discarding the idea. If you’re consistently encountering production issues, or you think you could improve your development process, then it’s worth giving it a shot. <strong>Try it for a limited amount of time, measure the impact, and compare the results.</strong> You may discover a method that helps you ship better software, and feel more confident about hitting the “Deploy” button.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66544710b50c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/an-introduction-to-tdd-with-vue-js-66544710b50c">An introduction to test-driven development with Vue.js</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to unit test your first Vue.js component]]></title>
            <link>https://medium.com/free-code-camp/how-to-unit-test-your-first-vue-js-component-14db6e1e360d?source=rss-20bd5f22250b------2</link>
            <guid isPermaLink="false">https://medium.com/p/14db6e1e360d</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sarah Dayan]]></dc:creator>
            <pubDate>Mon, 08 Oct 2018 00:02:51 GMT</pubDate>
            <atom:updated>2018-10-08T00:02:51.105Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HJnhZfsUqdgWcAMIlbqp-w.png" /><figcaption>Photo by <a href="https://unsplash.com/photos/V9sv7QrDUgc?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jefferson Santos</a> on <a href="https://unsplash.com/search/photos/jefferson-santos-code?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>.</figcaption></figure><p>In <a href="https://frontstuff.io/build-your-first-vue-js-component"><strong>Build Your First Vue.js Component</strong></a> we made a star rating component. We’ve covered many fundamental concepts to help you create more complex Vue.js components.</p><p>Yet, there’s one crucial point you need to build bulletproof components you can use in production: <strong>unit testing</strong>.</p><h3>Why unit test a component?</h3><p>Unit tests are a <strong>crucial</strong> part of continuous integration. They make your code a lot more reliable by focusing on small, isolated entities and making sure these always behave as expected. You can confidently iterate on your project without fear of breaking things.</p><p><strong>Unit tests aren’t limited to scripts.</strong> Anything we can test in isolation is unit testable, as long as you respect a few good practices. These practices include single-responsibility, predictability, and loose coupling.</p><p>As reusable entities of our app, <strong>Vue.js components are great candidates for unit testing</strong>. We’ll test the one we made as a single unit with various inputs and user interactions, and make sure it always behaves as we expect.</p><h3>Before we start</h3><p>A few things have changed since the <a href="https://frontstuff.io/build-your-first-vue-js-component">initial tutorial</a>. <a href="https://cli.vuejs.org/">Vue CLI 3</a> was released. <a href="https://vue-test-utils.vuejs.org/">Vue Test Utils</a> — the official Vue.js unit testing utility library — has matured to beta version. In the first tutorial, we used <a href="https://github.com/vuejs-templates/webpack-simple">webpack-simple</a>, a prototyping template that doesn’t include testing features. For these reasons, the simplest thing to do is to wipe the slate clean and migrate the project from the tutorial to a more recent Vue.js install.</p><p>I re-created the project from the first tutorial so you can download it directly from <a href="https://github.com/sarahdayan/star-rating-vue-js-tutorial">GitHub</a>. Then, navigate to the unzipped directory and install dependencies.</p><p><strong>Note:</strong> make sure you install <a href="https://nodejs.org/">Node.js</a> before going further:</p><pre>cd path/to/my/project npm install</pre><p>Then, run the project:</p><pre>npm run serve</pre><h3>Vue Test Utils and Jest</h3><p>For this tutorial, we’ll use <a href="https://vue-test-utils.vuejs.org/">Vue Test Utils</a>, the official Vue.js testing toolkit, along with <a href="https://jestjs.io/">Jest</a>, a JavaScript test runner backed by Facebook.</p><p>Vue Test Utils lets you mount Vue components in isolation and simulate user interactions. It has all the necessary utilities to test single-file components, including those using Vue Router or Vuex.</p><p>Jest is a full-featured test runner that requires almost no configuration. It also provides a built-in assertion library.</p><p>Vue CLI 3 (which I used to generate the <a href="https://github.com/sarahdayan/star-rating-vue-js-tutorial">boilerplate</a>) allows you to pick your favorite test runner, and sets it up for you. If you want to use another test runner (like <a href="https://mochajs.org/">Mocha</a>), install <a href="https://cli.vuejs.org/">Vue CLI 3</a> and generate your own starter project. Then you can migrate the source files from <a href="https://github.com/sarahdayan/star-rating-vue-js-tutorial">my boilerplate</a> right in it.</p><h3>What should we test?</h3><p>A common approach of unit testing is to <strong>only focus on the public API</strong> (aka black box testing). By overlooking implementation details, you’re allowing internals to change without having to adapt tests. After all, what you want to do is <strong>make sure your public API won’t break</strong>. What happens under the hood is indirectly tested, but all that matters is for the public API to remain reliable.</p><p>This is also the official recommendation from the <a href="https://vue-test-utils.vuejs.org/guides/#common-tips">Vue Test Utils guides</a>. Therefore, we’ll only test what we can access from the outside of the component:</p><ul><li>user interactions</li><li>props changes</li></ul><p>We won’t directly test computed properties, methods, or hooks. These will be implicitly tested by testing the public interface.</p><h3>Setting up a spec file</h3><p>Like with regular tests, each component has a spec file which describes all tests we want to run.</p><p>Specs are JavaScript files. By convention, they have the same name as the components they’re testing, plus a .spec suffix.</p><p>Go ahead and create a test/unit/Rating.spec.js file:</p><pre>// Rating.spec.js</pre><pre>import { shallowMount } from &#39;<a href="http://twitter.com/vue/test-utils">@vue/test-utils</a>&#39;<br>import Rating from &#39;@/components/Rating&#39;</pre><pre>describe(&#39;Rating&#39;, () =&gt; {<br>  // your tests go here<br>})</pre><p>We’ve imported our Rating component and shallowMount. The latter is a Vue Test Utils function which lets us mount our component without mounting its children.</p><p>The describe function call wraps all the test we’re about to write — it describes our <strong>testing suite</strong>. It has its own scope, and can itself wrap other nested suites.</p><p>Enough said, <strong>let’s start writing tests</strong>.</p><h3>Identifying testing scenarios</h3><p>When we look at Rating from the outside, we can see it does the following:</p><ul><li>it renders a list of stars which is equal to the value of the maxStars prop the user passes</li><li>it adds an active class to each star whose index is lower than or equal to the stars prop the user passes</li><li>it toggles the active class on a star when the user clicks it and removes it on the next stars</li><li>it toggles the icons star and star-o when the user clicks a star</li><li>it renders a counter if the user sets the hasCounter prop to true, hides it if they set it to false, and displays text saying how many stars of the maximum number of stars are currently active.</li></ul><p>Notice we’re only looking at what the component does from the outside. We don’t care that clicking a star executes the rate method, or that the internal stars data property changes. We could rename these, but this shouldn’t break our tests.</p><h3>Our first test</h3><p>Let’s write our first test. We first need to manually mount our component with shallowMount, and store it in a variable on which we’ll perform assertions. We can also pass props through the propsData attribute, as an object.</p><p>The mounted component is an object which comes with a handful of useful utility methods:</p><pre>describe(&#39;Rating&#39;, () =&gt; {<br>  const wrapper = shallowMount(Rating, {<br>    propsData: {<br>      maxStars: 6,<br>      grade: 3<br>    }<br>  })<br>  it(&#39;renders a list of stars with class `active` equal to prop.grade&#39;, () =&gt; {<br>    // our assertion goes here<br>  })<br>})</pre><p>Then, we can write our first assertion:</p><pre>it(&#39;renders a list of stars with class `active` equal to prop.grade&#39;, () =&gt; {<br>  expect(wrapper.findAll(&#39;.active&#39;).length).toEqual(3)<br>})</pre><p>Let’s analyze what’s happening here. First, we’re using Jest’s <a href="https://jestjs.io/docs/en/expect#expectvalue">expect</a> function, which takes the value we want to test as an argument. In our case, we call the <a href="https://vue-test-utils.vuejs.org/api/wrapper/#findall-selector">findAll</a> method on our wrapper to fetch all elements with an active class. This returns a <a href="https://vue-test-utils.vuejs.org/api/wrapper-array/">WrapperArray</a>, which is an object that contains an array of <a href="https://vue-test-utils.vuejs.org/api/wrapper/">Wrappers</a>.</p><p>A WrapperArray has two properties: wrappers (the contained Wrappers) and length (the number of Wrappers). The latter is what we need to have the expected number of stars.</p><p>The expect function also returns an object on which we can call methods to test the passed value. These methods are called <strong>matchers</strong>. Here, we use the toEqual matcher and pass it the expected value as in arguments. The method returns a boolean, which is what a test expects to either pass or fail.</p><p>To summarize, here we say we expect the total amount of elements with the class active we find in our wrapper to be equal to 3 (the value we assigned to the grade prop).</p><p>In your terminal, run your test:</p><pre>npm run test:unit</pre><p>You should see it pass 🎉</p><p>Time to write some more.</p><h3>Simulating user input</h3><p>Vue Test Utils makes it easy to simulate what real users end up doing in production. In our case, users can click on stars to toggle them. We can fake this in our tests with the trigger method, and dispatch all kinds of events.</p><pre>it(&#39;adds `active` class on an inactive star when the user clicks it&#39;, () =&gt; {<br>  const fourthStar = wrapper.findAll(&#39;.star&#39;).at(3)<br>  fourthStar.trigger(&#39;click&#39;)<br>  expect(fourthStar.classes()).toContain(&#39;active&#39;)<br>})</pre><p>Here, we first get our fourth star with findAll and <a href="https://vue-test-utils.vuejs.org/api/wrapper-array/#at-index">at</a>, which returns a Wrapper from a WrapperArray at the passed index (zero-based numbering). Then, we simulate the click event on it — we’re mimicking the action from a user who would click or tap the fourth star.</p><p>Since we set the grade prop to 3, the fourth star should be inactive before we click, therefore the click event should make it active. In our code, this is represented by a class active which we append on stars only when they’re activated. We test it by calling the <a href="https://vue-test-utils.vuejs.org/api/wrapper/#classes-classname">classes</a> method on the star, which returns its class names as an array of strings. Then, we use the <a href="https://jestjs.io/docs/en/expect#tocontainitem">toContain</a> matcher to make sure the active class is here.</p><h4>Setup and teardown</h4><p>Since we’ve triggered a click on our component, we’ve mutated its state. The problem is that we’re using that same component for all our tests. What happens if we change the order of our tests, and move this one to first position? Then the second test would fail.</p><p>You don’t want to rely on brittle things like order when it comes to tests. A test suite should be robust, and existing tests should ideally not change unless you’re breaking the API.</p><p>We want to make sure we always have a predictable wrapper to perform assertions on. We can achieve this with setup and teardown functions. These are helpers which let us initialize things before we run tests, and clean up afterward.</p><p>In our case, a way of doing it could be to create our wrapper before each test and destroy it afterwards.</p><pre>let wrapper = null</pre><pre>beforeEach(() =&gt; {<br>  wrapper = shallowMount(Rating, {<br>    propsData: {<br>      maxStars: 6,<br>      grade: 3<br>    }<br>  })<br>})</pre><pre>afterEach(() =&gt; {<br>  wrapper.destroy()<br>})</pre><pre>describe(&#39;Rating&#39;, () =&gt; {<br>  // we remove the `const wrapper = …` expression<br>  // …<br>}</pre><p>As their names suggest, <a href="https://jestjs.io/docs/en/api#beforeeachfn-timeout">beforeEach</a> and <a href="https://jestjs.io/docs/en/api#aftereachfn-timeout">afterEach</a> run before and after each test, respectively. This way we can be 100% sure we’re using a fresh wrapper whenever we run a new test.</p><h3>Special identifiers for tests</h3><p>It’s never a good idea to mix selectors for styling and other purposes, such as test hooks.</p><p>What if you change the tag name or the class?</p><p>What if you don’t have a specific identifier on an element you want to test such as, in our case, the counter?</p><p>You don’t want to pollute your production code with classes which would be useless there. It would be much better to have dedicated hooks for tests, such as a dedicated data attribute, <strong>but only during tests</strong>. This way a mess isn’t left in the final build.</p><p>One way to handle this is to create a <a href="https://vuejs.org/v2/guide/custom-directive.html">custom Vue directive</a>.</p><p>The Vue instance has a directive method which takes two arguments — a <strong>name</strong>, and an <strong>object of functions</strong> for each <a href="https://vuejs.org/v2/guide/custom-directive.html#Hook-Functions">hook of the component lifecycle</a> when injected in the DOM. You can also pass a single function if you don’t care about a specific hook.</p><p>Let’s create a new directory called directives in src/, and add a test.js file. We’ll export the function we want to pass in our directive.</p><pre>// test.js</pre><pre>export default (el, binding) =&gt; {<br>  // do stuff<br>}</pre><p>A directive hook can take <a href="https://vuejs.org/v2/guide/custom-directive.html#Directive-Hook-Arguments">several arguments</a> and, in our case, we only need the first two: el and binding. The el argument refers to the element the directive is bound to. The binding argument is an object which contains the data we passed in the directive. This way we can manipulate the element as we like.</p><pre>export default (el, binding) =&gt; {<br>  Object.keys(binding.value).forEach(value =&gt; {<br>    el.setAttribute(`data-test-${value}`, binding.value[value])<br>  })<br>}</pre><p>We’re passing an object to our directive, so we can generate data attributes starting with data-test-. In the handler function, we iterate over each property of binding, and we set a data attribute — based on the name and value — on our element.</p><p>Now we need to register our directive so we can use it. We can do it globally but, in our case, we’re only going to register it locally — right in our Rating.vue component.</p><pre>&lt;script&gt;<br>import Test from &#39;@/directives/test.js&#39;</pre><pre>export default {<br>  // …<br>  directives: { Test },<br>  // …<br>}<br>&lt;/script&gt;</pre><p>Our directive is now accessible under the v-test name. Try setting the following directive on the counter:</p><pre>&lt;span v-test=&quot;{ id: &#39;counter&#39; }&quot; v-if=&quot;hasCounter&quot;&gt;<br>  {{ stars }} of {{ maxStars }}<br>&lt;/span&gt;</pre><p>Now inspect the HTML in your browser with the developer tools. Your counter should look like this:</p><pre>&lt;span data-test-id=&quot;counter&quot;&gt;2 of 5&lt;/span&gt;</pre><p>Great, it works! Now, we don’t need this either in dev mode nor when we build the project. The sole purpose of this data attribute is to be able to target elements during tests, so we only want to set it up when we run them. For this, we can use the NODE_ENV environment variable provided by Webpack, the module bundler powering our project.</p><p>When we run tests, NODE_ENV is set to &#39;test&#39;. Therefore, we can use it to determine when to set the test attributes or not.</p><pre>export default (el, binding) =&gt; {<br>  if (process.env.NODE_ENV === &#39;test&#39;) {<br>    Object.keys(binding.value).forEach(value =&gt; {<br>      el.setAttribute(`data-test-${value}`, binding.value[value])<br>    })<br>  }<br>}</pre><p>Refresh your app in the browser and inspect the counter again: <strong>the data attribute is gone</strong>.</p><p>Now we can use the v-test directive for all elements we need to target. Let’s take our test from earlier:</p><pre>it(&#39;adds `active` class on an inactive star when the user clicks it&#39;, () =&gt; {<br>  const fourthStar = wrapper.findAll(&#39;[data-test-id=&quot;star&quot;]&#39;).at(3)<br>  fourthStar.trigger(&#39;click&#39;)<br>  expect(fourthStar.classes()).toContain(&#39;active&#39;)<br>})</pre><p>We’ve replaced the .star selector with [data-test-id=&quot;star&quot;], which allows us to change classes for presentation purposes without breaking tests. We get one of the benefits of the <a href="https://en.wikipedia.org/wiki/Single_responsibility_principle">single-responsibility principle</a> and loose <a href="https://en.wikipedia.org/wiki/Coupling_(computer_programming)">coupling</a> — when your abstractions only have a single reason to change, you avoid all kinds of pesky side-effects.</p><h3>Should we also use these hooks for the classes we test?</h3><p>After setting this directive to target elements to test, you may be wondering if you should also use them to replace the classes we actively look for. Let’s look at the assertion from our first test:</p><pre>expect(wrapper.findAll(&#39;.active&#39;).length).toEqual(3)</pre><p>Should we use v-test on the elements with the active class, and replace the selector in the assertion? <strong>Great question</strong>.</p><p>Unit tests are all about testing one thing at a time. The first argument of the it function is a string, with which we describe what we’re doing <strong>from a consumer perspective</strong>.</p><p>The test that wraps our assertion says renders a list of stars with class active equal to prop.grade. This is what the consumer expects. When they pass a number to the grade property, they expect to retrieve an <strong>equal number</strong> of active or selected stars. Yet, in our component’s logic, the active class is precisely what we use to define this trait. We assign it depending on a specific condition, so we can visually differentiate active stars from the others. Here, the presence of this specific class is exactly what we want to test.</p><p>So, when deciding whether you should use a selector you already have or set a v-test directive, ask yourself the question: <strong>what am I testing, and does using this selector makes sense for a business logic perspective?</strong></p><h3>How is it different from functional or end-to-end tests?</h3><p>At first, it might look odd to unit test components. Why would you unit test UI and user interactions? Isn’t that what functional tests are here for?</p><p>There is a fundamental yet subtle difference to make between testing a component’s public API — aka from a <strong>consumer</strong> perspective — and testing a component from a <strong>user</strong> perspective. First, let’s underline something important: <strong>we’re testing well-defined JavaScript functions, not pieces of UI</strong>.</p><p>When you look at a single-file component it’s easy to forget the component compiles into a JavaScript function. We’re not testing the underlying Vue mechanism which, from this function, causes UI-oriented side-effects like injecting HTML in the DOM. That’s what Vue’s own tests already take care of. In our case, our component is no different from any other function: <strong>it accepts input and returns an output</strong>. These causes and consequences are what we’re testing, and nothing else.</p><p>What’s confusing is that our tests look a bit different from regular unit tests. Usually, we write things like:</p><pre>expect(add(3)(4)).toEqual(7)</pre><p>There’s no debate here. Input and output of data, that’s all we care about. With components, we’re expecting things to render visually. We’re traversing a virtual DOM and testing for the presence of nodes. That’s also what you do with functional or end-to-end tests, with tools like <a href="https://www.seleniumhq.org/">Selenium</a> or <a href="https://www.cypress.io/">Cypress.io</a>. So how does that differ?</p><p>You need not to confuse <strong>what</strong> we’re doing to fetch the data we want to test and the actual <strong>purpose</strong> of the test. <strong>With unit tests, we’re testing isolated behaviors. With functional or end-to-end tests, we’re testing scenarios</strong>.</p><p>A unit test makes sure a <strong>unit</strong> of the program behaves as expected. It’s addressed to the <strong>consumer</strong> of the component — the programmer who uses the component in their software. A functional test ensures a <strong>feature</strong> or a <strong>workflow</strong> behaves as expected, from a <strong>user</strong> perspective — the final user, who consumes the full software.</p><h3>Going further</h3><p>I won’t go into the detail of each test, because they all share a similar structure. You can find the <a href="https://github.com/sarahdayan/star-rating-vue-js-tutorial/blob/tests/tests/unit/Rating.spec.js">full spec file on GitHub</a>, and I strongly recommend you try to implement them yourself first. Software testing is an art as much as it is a science, and requires twice as much practice as it requires theory.</p><p>Don’t worry if you didn’t get everything, or if you struggle with writing your first tests: <strong>testing is notoriously hard</strong>. Also, if you have a question, don’t hesitate to hit me up on <a href="https://twitter.com/frontstuff_io">Twitter</a>!</p><p>Originally published at <a href="https://frontstuff.io/unit-test-your-first-vuejs-component">frontstuff.io</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14db6e1e360d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/how-to-unit-test-your-first-vue-js-component-14db6e1e360d">How to unit test your first Vue.js component</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I dropped 250KB of dead CSS weight with PurgeCSS]]></title>
            <link>https://medium.com/free-code-camp/how-i-dropped-250kb-of-dead-css-weight-with-purgecss-28821049fb?source=rss-20bd5f22250b------2</link>
            <guid isPermaLink="false">https://medium.com/p/28821049fb</guid>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[tailwind]]></category>
            <category><![CDATA[utility-first]]></category>
            <dc:creator><![CDATA[Sarah Dayan]]></dc:creator>
            <pubDate>Tue, 03 Jul 2018 14:42:35 GMT</pubDate>
            <atom:updated>2018-07-03T14:42:35.490Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UHrztp4ppPEPiHl_Zwo2Mg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/ASEaTdVIvBQ?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Lena L</a> on <a href="https://unsplash.com/search/photos/balloon-helium?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I’m <a href="https://frontstuff.io/in-defense-of-utility-first-css">a big advocate for utility-first CSS</a>. After trying several methods over the years, it’s what I’ve found to be <strong>the best, most maintainable and scalable way of writing CSS to this day</strong>.</p><p>When my coworker <a href="https://github.com/clemfromspace">Clément Denoix</a> and I built <a href="https://www.api-search.io/">api-search.io</a>, I decided to use <a href="https://tailwindcss.com/">Tailwind CSS</a> to style it. Tailwind CSS is a theme-agnostic, fully customizable, utility-first library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2WQMgDsMgYhNHRqw.png" /></figure><p>The whole point of a library is to give you access to a broad set of tools to use at will. The problem is, since you usually use only a subset of it, <strong>you end up with a lot of unused CSS rules in your final build</strong>.</p><p>In my case, not only did I load the entire Tailwind CSS library, but I also added several variants to some modules. That ended up making the final minified CSS file weight <strong>259 KB</strong> (before GZip). That’s quite heavy when you consider that the website is a simple single-page app with a minimal design.</p><p>You don’t want to load each utility by hand when you need it. That would be a long and cumbersome task. A better scenario is to have everything at your disposal during development and <strong>automatically remove what you didn’t use during the build step</strong>.</p><p>In JavaScript, we call it <a href="https://developer.mozilla.org/en-US/docs/Glossary/Tree_shaking">tree-shaking</a>. Now, thanks to <a href="https://www.purgecss.com/">PurgeCSS</a>, <strong>you can do the same with your CSS codebase</strong>.</p><p>PurgeCSS analyzes your content files and your CSS, then matches the selectors together. If it doesn’t find any occurrence of a selector in the content, it removes it from the CSS file.</p><p>For the most part, <strong>this can work out of the box</strong>. However, there are some areas in any website that may require some more thinking before letting PurgeCSS do its magic.</p><h3>Splitting my CSS</h3><p>The project contains three main CSS files:</p><ul><li>A CSS reset called <a href="https://github.com/necolas/normalize.css">normalize.css</a>, included in Tailwind CSS.</li><li><a href="https://tailwindcss.com/">Tailwind CSS</a>, the most substantial part of my CSS codebase.</li><li>Some custom CSS, mostly for styling the <a href="https://community.algolia.com/react-instantsearch/">InstantSearch</a> components to which I couldn’t add classes.</li></ul><p>PurgeCSS can’t detect that I need to keep selectors such as .ais-Highlight, <strong>because the components that use it only show up in the DOM at runtime</strong>. Same goes with normalize.css: I’m relying on it to reset browser styles, but many of the related components will never be matched because they’re generated in JavaScript.</p><p>In the case of classes starting with .ais-, we can sort them out with <a href="https://frontstuff.io/how-i-dropped-250-kb-of-dead-css-weight-with-purgecss#whitelisting-runtime-classes">whitelisting</a>. Now when it comes to reset styles, selectors are a bit trickier to track down. Plus, the size of normalize.css is pretty insignificant and isn’t bound to change. So in this case, I decided to ignore the file altogether. Consequently, <strong>I had to split styles before running PurgeCSS</strong>.</p><p>My initial CSS configuration looked like this:</p><ul><li>A tailwind.src.css file with three @tailwind directives: preflight, components and utilities.</li><li>An App.css file with my custom styles.</li><li>An npm script in package.json to build Tailwind CSS right before starting or building the project. Every time this script runs, it outputs a tailwind.css file in src, which is loaded in the project.</li></ul><p>The @tailwind preflight directive loads normalize.css. I didn’t want PurgeCSS to touch it, so I moved it to a separate file.</p><pre>// tailwind.src.css <a href="http://twitter.com/tailwind">@tailwind</a> components;</pre><pre><a href="http://twitter.com/tailwind">@tailwind</a> utilities;/* normalize.src.css */ <a href="http://twitter.com/tailwind">@tailwind</a> preflight;</pre><p>Then, I changed my existing tailwind script in package.json to build normalize.src.css separately.</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;tailwind&quot;: &quot;npm run tailwind:normalize &amp;&amp; npm run tailwind:css&quot;,<br>    &quot;tailwind:normalize&quot;: &quot;tailwind build src/normalize.src.css -c tailwind.js -o src/normalize.css&quot;,<br>    &quot;tailwind:css&quot;: &quot;tailwind build src/tailwind.src.css -c tailwind.js -o src/tailwind.css&quot;<br>  }<br>}</pre><p>Finally, I loaded normalize.css in the project.</p><pre>// src/index.js</pre><pre>...<br>import &#39;./normalize.css&#39;<br>import &#39;./tailwind.css&#39;<br>import App from &#39;./App&#39;<br>...</pre><p>Now, I can run PurgeCSS on tailwind.css without fearing it might strip down needed rulesets.</p><h3>Configuring PurgeCSS</h3><p>PurgeCSS comes in many flavors: a command-line interface, a JavaScript API, wrappers for Webpack, Gulp, Rollup, and so on.</p><p>We used <a href="https://github.com/facebook/create-react-app">Create React App</a> to bootstrap the website, so Webpack came <a href="https://github.com/facebook/create-react-app#get-started-immediately">preconfigured and hidden</a> behind <a href="https://www.npmjs.com/package/react-scripts">react-scripts</a>. This means I couldn’t access Webpack configuration files unless I ran npm run eject to get them back and manage them directly in the project.</p><p>Not having to manage Webpack yourself has many advantages, so ejecting wasn’t an option. Instead, I decided to use a custom configuration file for PurgeCSS, and an npm script.</p><p>I first created a purgecss.config.js at the root of the project:</p><pre>module.exports = {<br>  content: [&#39;src/App.js&#39;],<br>  css: [&#39;src/tailwind.css&#39;]<br>}</pre><ul><li>The content property takes an array of files to analyze to match CSS selectors.</li><li>The css property takes an array of stylesheets to purge.</li></ul><p>Then, I edited my npm scripts to run PurgeCSS:</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;npm run css &amp;&amp; react-scripts start&quot;,<br>    &quot;build&quot;: &quot;npm run css &amp;&amp; react-scripts build&quot;,<br>    &quot;css&quot;: &quot;npm run tailwind &amp;&amp; npm run purgecss&quot;,<br>    &quot;purgecss&quot;: &quot;purgecss -c purgecss.config.js -o src&quot;<br>  }<br>}</pre><ul><li>I added a purgecss script that takes my configuration file and outputs the purged stylesheet in src.</li><li>I made this script run every time we start or build the project.</li></ul><p>Tailwind CSS uses special characters, so if you use PurgeCSS out of the box, it may remove necessary selectors. Fortunately, PurgeCSS allows us to use a <a href="https://www.purgecss.com/extractors#creating-an-extractor">custom extractor</a>, which is a function that lists out the selectors used in a file. For Tailwind, I needed to create a <a href="https://tailwindcss.com/docs/controlling-file-size/">custom one</a>:</p><pre>module.exports = {<br>  ...<br>  extractors: [<br>    {<br>      extractor: class {<br>        static extract(content) {<br>          return content.match(/[A-z0-9-:\/]+/g) || []<br>        },<br>        extensions: [&#39;js&#39;]<br>      }<br>    }<br>  ]<br>}</pre><h3>Whitelisting runtime classes</h3><p><strong>PurgeCSS can’t detect classes that are generated at runtime</strong>, but it lets you define a whitelist. The classes you whitelist remain in the final file no matter what.</p><p>The project uses <a href="https://community.algolia.com/react-instantsearch/">React InstantSearch</a>, which generates components with classes that all start with ais-. Conveniently, PurgeCSS supports patterns in the form of regular expressions.</p><pre>module.exports = {<br>  ...<br>  css: [&#39;src/tailwind.css&#39;, &#39;src/App.css&#39;],<br>  whitelistPatterns: [/ais-.*/],<br>  ...<br>}</pre><p>Now if I forget to remove a class that I no longer use from App.css, it will be taken out from the final build, but my InstantSearch selectors will remain safe.</p><h3>New build, lighter CSS</h3><p>With this new configuration, <strong>my final CSS file has gone from 259 KB to…9 KB!</strong> It’s pretty significant in the context of a whole project, especially since many countries still have slow and unstable Internet, and more and more people browse on their phones while on the move.</p><p>Accessibility is also about catering for people with low bandwidth connections. It’s not acceptable not to try and help your users with slower Internet, especially if what you’re making them download is dead code.</p><p>That’s worth taking a moment to optimize your build. 🙂</p><p><em>Originally published at </em><a href="https://frontstuff.io/how-i-dropped-250-kb-of-dead-css-weight-with-purgecss"><em>frontstuff.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28821049fb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/how-i-dropped-250kb-of-dead-css-weight-with-purgecss-28821049fb">How I dropped 250KB of dead CSS weight with PurgeCSS</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to decide whether you should chain or extend CSS classes]]></title>
            <link>https://medium.com/free-code-camp/how-to-decide-whether-you-should-chain-or-extend-css-classes-a8e17d7a7b0b?source=rss-20bd5f22250b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8e17d7a7b0b</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Sarah Dayan]]></dc:creator>
            <pubDate>Thu, 24 May 2018 21:38:53 GMT</pubDate>
            <atom:updated>2018-05-24T21:38:53.575Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F4cl96xj67BOs1-4QVq0Rg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/-inuQpBGbgI?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Alexandru Tugui</a> on <a href="https://unsplash.com/search/photos/chain?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>If you’re building an app or a website that changes often, modular CSS methods solve many issues. Instead of copying your HTML structure in CSS and decorating it, you create consumable libraries of components. This makes projects more scalable and keeps the CSS codebase under control.</p><p>CSS modularity relies on composition, which inevitably fattens the HTML. This collateral effect can be a significant deterrent for many people because of the “bloat” it creates.</p><p>In this article, we’ll compare two techniques: <strong>chaining</strong> and <strong>extending</strong>. We’ll see what they provide and what their shortcomings are so that you can make more informed choices.</p><h3>Chaining</h3><p>Chaining CSS classes means <strong>composing the desired look by adding granular modifiers together onto an HTML selector</strong>. The composite styles create the final visual outcome. This is the default behavior with most modular CSS methodologies.</p><p>Let’s take the following OOCSS code for a button:</p><pre>.btn {<br>  display: block;<br>  box-shadow: 0 0 5px 0 rgba(0, 0, 0, .2);<br>}<br>.btn-default {<br>  border: 3px solid grey;<br>}<br>.btn-primary {<br>  background: purple; color: white;<br>}</pre><p>If you were to chain modifiers, your HTML would look like this:</p><pre>&lt;button class=&quot;btn btn-primary&quot;&gt;Primary button&lt;/button&gt;<br>&lt;button class=&quot;btn btn-default&quot;&gt;Default button&lt;/button&gt;</pre><p>Now let’s do something a bit more complex, this time with BEM (block, element, modifier):</p><pre>&lt;div class=&quot;media-object media-object--reverse media-object--outlined&quot;&gt;<br>  &lt;div class=&quot;media-object__media&quot;&gt;<br>    &lt;img class=&quot;media-object__img media-object__img--faded img img--square&quot; src=&quot;...&quot; alt=&quot;...&quot;&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;media-object__body&quot;&gt;...&lt;/div&gt;<br>&lt;/div&gt;</pre><p>Here we have a lot more interacting classes:</p><ul><li>The .media-object block has several modifiers (.media-object--reverse and .media-object--outlined).</li><li>The .media-object__img element has one modifier (.media-object__img--faded).</li><li>The .media-object__img element is also an .img block with its own modifier (.img--square).</li></ul><h4>Pros</h4><p>The top highlight of chaining classes is <strong>separate responsibility</strong>. It keeps your CSS codebase clean, light, comfortable to read, and non-repetitive. What each class does is crystal clear, and you immediately know what you should use and what you shouldn’t.</p><p><strong>It also prevents dead code: since you’re dealing with building blocks, everything is potentially useful.</strong> When you remove a component, you only need to remove the HTML.</p><p>Separate modifiers are great to represent state. Thus it makes life easier for JavaScript engineers. All they have to do is add and remove classes.</p><p>On large projects, <strong>this method can save you a lot of time</strong>.</p><h4>Cons</h4><p>One of the most common issues people have with modular CSS is that it creates “class madness” in the HTML. Strictly speaking, this is true.</p><p>Design patterns that split responsibilities almost always result in more files and verbose code. CSS is no exception: <strong>if you pick a method that’s supposed to make your codebase more maintainable, the counterpart is lengthy HTML files</strong>.</p><p>Having to type so much code is becoming less and less of a problem these days, as most editors and IDEs offer powerful autocompletion. But now, it’s still more code to write every time you make a new page or compose a new component. Over time, this can induce a feeling of clutter and redundancy that will put off some developers.</p><h3>Extending</h3><p>If you don’t want to chain classes, you can extend them. We still have the same separate blocks, but instead of chaining them in the HTML, <strong>we inherit the properties of the base class to its modifiers</strong>. This way, we can use them all at once.</p><p>Let’s use the @extend function in Sass to do so:</p><pre>.btn {<br>  display: block;<br>  box-shadow: 0 0 5px 0 rgba(0, 0, 0, .2);<br>  &amp;-default {<br>    <a href="http://twitter.com/extend">@extend</a> .btn;<br>    border: 3px solid grey;<br>  }<br>  &amp;-primary {<br>    <a href="http://twitter.com/extend">@extend</a> .btn;<br>    background: purple;<br>    color: white;<br>  }<br>}</pre><p>This will turn into the following CSS snippet:</p><pre>.btn,<br>.btn-default,<br>.btn-primary {<br>  display: block;<br>  box-shadow: 0 0 5px 0 rgba(0, 0, 0, .2);<br>}<br>.btn-default {<br>  border: 3px solid grey;<br>}<br>.btn-primary {<br>  background: purple; color: white;<br>}</pre><p>With the above CSS, our HTML would look like this:</p><pre>&lt;button class=&quot;btn-primary&quot;&gt;Primary button&lt;/button&gt;<br>&lt;button class=&quot;btn-default&quot;&gt;Default button&lt;/button&gt;</pre><p>Instead of having a slew of seemingly repetitive classes, we only have one. It has an explicit name and keeps the code readable. We can still use .btn alone, but if we need a variation of it, we only need to append the modifier part on it instead of chaining a new class.</p><h4>Pros</h4><p><strong>The highlight of this method is a clutter-free, more readable, and lighter HTML.</strong> When you go for modular CSS, you also decide to do more HTML and less CSS. The CSS becomes a library instead of a list of instructions. Thus, you spend more time in the HTML, which is why you may want to keep it light and easy to read.</p><h4>Cons</h4><p>Your CSS may <strong>look</strong> DRY, especially if you’re using a pre-processor, but <strong>extending classes results in a much heavier CSS file</strong>. Plus, you don’t have much control over what happens: every time you use @extend, the class definition is moved to the top and added to a list of selectors sharing the same ruleset. This process can result in weird style overrides and a lot more generated code.</p><p>There’s also the case of wanting to use several modifiers together. With the extend method, you don’t compose in the HTML anymore. You’re left with one solution if you’re going to create new combinations: create even more classes by extending modifiers. <strong>This is hard to maintain and results in more code.</strong> Every time you need to blend classes, you’ll need to edit the CSS and create a potentially non-reusable new rule. If you ever remove the HTML that uses it, you’ll also have to delete the CSS class.</p><h3>Afterthoughts</h3><p><strong>Modular CSS comes at the price of more verbose HTML,</strong> but it’s not much to pay for all the benefits it provides. If you’ve already determined you need modularity, don’t shoot yourself in the foot by using incompatible practices. It will result in more work for half the benefits. Inheritance is tempting, but <a href="https://en.wikipedia.org/wiki/Composition_over_inheritance">composition has more than once been recognized as a far better strategy</a>.</p><p>HTML “bloat” is not that big of a deal when you look at its actual impact. Modularity inevitably creates more code — the method you pick only determines <strong>where</strong> it goes. From a performance standpoint, <a href="https://frontstuff.io/in-defense-of-utility-first-css#it-bloats-the-html">more HTML is far better than more CSS</a>.</p><p><strong>Don’t focus on small things that don’t matter.</strong> Instead, leverage tools that help you write and navigate code more efficiently. Try to look at the big picture and make choices based on facts, not personal preferences.</p><p><em>Originally published at </em><a href="https://frontstuff.io/should-you-chain-or-extend-css-classes"><em>frontstuff.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8e17d7a7b0b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/how-to-decide-whether-you-should-chain-or-extend-css-classes-a8e17d7a7b0b">How to decide whether you should chain or extend CSS classes</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a shopping cart with Vue and Dinero.js]]></title>
            <link>https://medium.com/free-code-camp/how-to-build-a-shopping-cart-with-vue-and-dinero-js-22a7dc4c5352?source=rss-20bd5f22250b------2</link>
            <guid isPermaLink="false">https://medium.com/p/22a7dc4c5352</guid>
            <category><![CDATA[money]]></category>
            <category><![CDATA[payments]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Sarah Dayan]]></dc:creator>
            <pubDate>Wed, 09 May 2018 17:50:54 GMT</pubDate>
            <atom:updated>2018-05-09T17:50:54.661Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zXIPhALV594QhOVSEBVRGA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/fJTqyZMOh18?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Allef Vinicius</a> on <a href="https://unsplash.com/search/photos/checkout-money?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>My friend <a href="https://twitter.com/corydhmiller">Cory</a> and I chat almost every day, so you can bet he knows about everything going on in my life. But as we were talking the other day, I realized <strong>he had no idea how </strong><a href="https://github.com/sarahdayan/dinero.js"><strong>Dinero.js</strong></a><strong>, my latest project, actually works</strong>. Like, what you can do with it.</p><p>I paused and realized it may actually not be <em>that</em> obvious. It’s easier, whatever your skill level is, to understand what a smooth scrolling plugin does than what a money library has to offer.</p><blockquote>“Do you see in JavaScript how you can use a Date constructor to store a date and format it later? Or you use Moment.js to create moment objects and how it’s better than storing dates as strings or any other type?</blockquote><blockquote>Well, <strong>Dinero.js is like Moment, but for money</strong>. There’s no native way to handle money, and if you try to do it with Number types, you’re going to run into issues. That’s what Dinero.js helps you avoid. It secures your monetary values in objects and allows you to do whatever you need with them.”</blockquote><p>I was happy with my explanation, as Cory started <em>“a-ha”</em>-ing. But I realized one thing had been missing from the beginning. Something that would speak volumes and help anyone understand the benefits of Dinero.js: a <strong>real-world example</strong>.</p><p>In this tutorial, we’ll build a <strong>shopping cart</strong>. We’ll use Vue.js to build the component, then integrate Dinero.js to handle all the money stuff.</p><p><strong><em>TL;DR:</em></strong> <em>this post goes in-depth in the how and why. It’s designed to help you grasp the core concepts of Dinero.js. If you want to understand the whole thought process, read on. Otherwise you can look at the final code on </em><a href="https://codesandbox.io/s/ojvmp7ryk5"><em>CodeSandbox</em></a><em>.</em></p><p>This post assumes you have basic knowledge of Vue.js. If not, first check my tutorial <a href="https://frontstuff.io/build-your-first-vue-js-component">“Build Your First Vue.js Component</a>.” It will equip you with everything you need to go further.</p><h3>Getting started</h3><p>For this project, we’ll use <a href="https://github.com/vuejs/vue-cli">vue-cli</a> and the <a href="https://github.com/vuejs-templates/webpack-simple">webpack-simple</a> Vue.js template. If you don’t have vue-cli installed globally on your machine, fire up your terminal and type the following:</p><pre>npm install -g vue-cli</pre><p>Then:</p><pre>vue init webpack-simple path/to/my-project</pre><p>You can keep the default options for all questions. When it’s done, navigate to the new directory, install dependencies, and run the project:</p><pre>cd path/to/my-project npm install npm run dev</pre><p>Webpack will start serving your project on port 8080 (if available) and open it in your browser.</p><h3>Setting up the HTML/CSS</h3><p><strong>I won’t get into page structure and styling in this tutorial</strong>, so I invite you to copy/paste the code. Open the App.vue file, and paste the following snippets.</p><p>This goes between the &lt;template&gt; tags:</p><pre>&lt;div id=&quot;app&quot;&gt;<br>  &lt;div class=&quot;cart&quot;&gt;<br>    &lt;h1 class=&quot;title&quot;&gt;Order&lt;/h1&gt;<br>    &lt;ul class=&quot;items&quot;&gt;<br>      &lt;li class=&quot;item&quot;&gt;<br>        &lt;div class=&quot;item-preview&quot;&gt;<br>          &lt;img src=&quot;&quot; alt=&quot;&quot; class=&quot;item-thumbnail&quot;&gt;<br>          &lt;div&gt;<br>            &lt;h2 class=&quot;item-title&quot;&gt;&lt;/h2&gt;<br>            &lt;p class=&quot;item-description&quot;&gt;&lt;/p&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;div&gt;<br>          &lt;input type=&quot;text&quot; class=&quot;item-quantity&quot;&gt;<br>          &lt;span class=&quot;item-price&quot;&gt;&lt;/span&gt;<br>        &lt;/div&gt;<br>      &lt;/li&gt;<br>    &lt;/ul&gt;<br>    &lt;h3 class=&quot;cart-line&quot;&gt;<br>      Subtotal &lt;span class=&quot;cart-price&quot;&gt;&lt;/span&gt;<br>    &lt;/h3&gt;<br>    &lt;h3 class=&quot;cart-line&quot;&gt;<br>      Shipping &lt;span class=&quot;cart-price&quot;&gt;&lt;/span&gt;<br>    &lt;/h3&gt;<br>    &lt;h3 class=&quot;cart-line&quot;&gt;<br>      Total &lt;span class=&quot;cart-price cart-total&quot;&gt;&lt;/span&gt;<br>    &lt;/h3&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>Ant this between the &lt;style&gt; tags:</p><pre>body {<br>  margin: 0;<br>  background: #fdca40;<br>  padding: 30px;<br>}</pre><pre>.title {<br>  display: flex;<br>  justify-content: space-between;<br>  align-items: center;<br>  margin: 0;<br>  text-transform: uppercase;<br>  font-size: 110%;<br>  font-weight: normal;<br>}</pre><pre>.items {<br>  margin: 0;<br>  padding: 0;<br>  list-style: none;<br>}</pre><pre>.cart {<br>  background: #fff;<br>  font-family: &#39;Helvetica Neue&#39;, Arial, sans-serif;<br>  font-size: 16px;<br>  color: #333a45;<br>  border-radius: 3px;<br>  padding: 30px;<br>}<br>.cart-line {<br>  display: flex;<br>  justify-content: space-between;<br>  align-items: center;<br>  margin: 20px 0 0 0;<br>  font-size: inherit;<br>  font-weight: normal;<br>  color: rgba(51, 58, 69, 0.8);<br>}<br>.cart-price {<br>  color: #333a45;<br>}<br>.cart-total {<br>  font-size: 130%;<br>}</pre><pre>.item {<br>  display: flex;<br>  justify-content: space-between;<br>  align-items: center;<br>  padding: 15px 0;<br>  border-bottom: 2px solid rgba(51, 58, 69, 0.1);<br>}<br>.item-preview {<br>  display: flex;<br>  align-items: center;<br>}<br>.item-thumbnail {<br>  margin-right: 20px;<br>  border-radius: 3px;<br>}<br>.item-title {<br>  margin: 0 0 10px 0;<br>  font-size: inherit;<br>}<br>.item-description {<br>  margin: 0;<br>  color: rgba(51, 58, 69, 0.6);<br>}<br>.item-quantity {<br>  max-width: 30px;<br>  padding: 8px 12px;<br>  font-size: inherit;<br>  color: rgba(51, 58, 69, 0.8);<br>  border: 2px solid rgba(51, 58, 69, 0.1);<br>  border-radius: 3px;<br>  text-align: center;<br>}<br>.item-price {<br>  margin-left: 20px;<br>}</pre><h3>Adding data</h3><p>When you’re dealing with products, you usually retrieve raw data from a database or an API. We can get close by representing it in a separate JSON file, then importing it asynchronously as if we were querying an API.</p><p>Let’s create a products.json file in assets/ and add the following:</p><pre>{<br>  &quot;items&quot;: [<br>    {<br>      &quot;title&quot;: &quot;Item 1&quot;,<br>      &quot;description&quot;: &quot;A wonderful product&quot;,<br>      &quot;thumbnail&quot;: &quot;<a href="https://fakeimg.pl/80x80">https://fakeimg.pl/80x80</a>&quot;,<br>      &quot;quantity&quot;: 1,<br>      &quot;price&quot;: 20<br>    },<br>    {<br>      &quot;title&quot;: &quot;Item 2&quot;,<br>      &quot;description&quot;: &quot;A wonderful product&quot;,<br>      &quot;thumbnail&quot;: &quot;<a href="https://fakeimg.pl/80x80">https://fakeimg.pl/80x80</a>&quot;,<br>      &quot;quantity&quot;: 1,<br>      &quot;price&quot;: 15<br>    },<br>    {<br>      &quot;title&quot;: &quot;Item 3&quot;,<br>      &quot;description&quot;: &quot;A wonderful product&quot;,<br>      &quot;thumbnail&quot;: &quot;<a href="https://fakeimg.pl/80x80">https://fakeimg.pl/80x80</a>&quot;,<br>      &quot;quantity&quot;: 2,<br>      &quot;price&quot;: 10<br>    }<br>  ],<br>  &quot;shippingPrice&quot;: 20<br>}</pre><p><strong>This is pretty similar to what we would get from a real API:</strong> data as a collection, with titles and text as strings, and quantity and prices as numbers.</p><p>We can go back to App.vue and set empty values in data. This will allow the template to initialize while the actual data is being fetched.</p><pre>data() {<br>  return {<br>    data: {<br>      items: [],<br>      shippingPrice: 0<br>    }<br>  }<br>}</pre><p>Finally, we can fetch data from products.json with an asynchronous request, and update the data property when it’s ready:</p><pre>export default {<br>  ...<br>  created() {<br>    fetch(&#39;./src/assets/products.json&#39;)<br>      .then(response =&gt; response.json())<br>      .then(json =&gt; (this.data = json))<br>  }<br>}</pre><p>Now let’s populate our template with this data:</p><pre>&lt;ul class=&quot;items&quot;&gt;<br>  &lt;li :key=&quot;item.id&quot; v-for=&quot;item in data.items&quot; class=&quot;item&quot;&gt;<br>    &lt;div class=&quot;item-preview&quot;&gt;<br>      &lt;img :src=&quot;item.thumbnail&quot; :alt=&quot;item.title&quot; class=&quot;item-thumbnail&quot;&gt;<br>      &lt;div&gt;<br>        &lt;h2 class=&quot;item-title&quot;&gt;{{ item.title }}&lt;/h2&gt;<br>        &lt;p class=&quot;item-description&quot;&gt;{{ item.description }}&lt;/p&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;div&gt;<br>      &lt;input type=&quot;text&quot; class=&quot;item-quantity&quot; v-model=&quot;item.quantity&quot;&gt;<br>      &lt;span class=&quot;item-price&quot;&gt;{{ item.price }}&lt;/span&gt;<br>    &lt;/div&gt;<br>  &lt;/li&gt;<br>&lt;/ul&gt;<br>...<br>&lt;h3 class=&quot;cart-line&quot;&gt;<br>  Shipping<br>  &lt;span class=&quot;cart-price&quot;&gt;{{ data.shippingPrice }}&lt;/span&gt;<br>&lt;/h3&gt;<br>...</pre><p><strong>You should see all the items in your cart.</strong> Now let’s add some computed properties to calculate the subtotal and total:</p><pre>export default {<br>  ...<br>  computed: {<br>    getSubtotal() {<br>      return this.data.items.reduce(<br>        (a, b) =&gt; a + b.price * b.quantity,<br>        0<br>      )<br>    },<br>    getTotal() {<br>      return (<br>        this.getSubtotal + this.data.shippingPrice<br>      )<br>    }<br>  }<br>}</pre><p>And add them to our template:</p><pre>&lt;h3 class=&quot;cart-line&quot;&gt;<br>  Subtotal<br>  &lt;span class=&quot;cart-price&quot;&gt;{{ getSubtotal }}&lt;/span&gt;<br>&lt;/h3&gt;<br>...<br>&lt;h3 class=&quot;cart-line&quot;&gt;<br>  Total<br>  &lt;span class=&quot;cart-price cart-total&quot;&gt;{{ getTotal }}&lt;/span&gt;<br>&lt;/h3&gt;</pre><p>There we go! Try changing quantities around — you should see the subtotal and total amounts change accordingly.</p><p><strong>Now we have a few issues here.</strong> First, we’re only showing amounts, not currencies. Sure, we could hard code them in the template right next to the reactive amounts. But what if we want to make a multi-lingual website? Not all languages format money the same way.</p><p>What if we want to show all amounts with two decimal places, for better alignment? You could try and keep all initial amounts as floats by using the toFixed method, but then you’d be working with String types which are a lot harder and less performant when it comes to doing math. Also, that would mean changing data for purely presentational purposes, which never is a good idea. What if you need the same data for other purposes and it requires a different format?</p><p>Finally, the current solution is relying on floating point math, <strong>which is a </strong><a href="https://frontstuff.io/how-to-handle-monetary-values-in-javascript"><strong>bad idea when it comes to handling money</strong></a>. Try and change a few amounts:</p><pre>{<br>  &quot;items&quot;: [<br>    {<br>      ...<br>      &quot;price&quot;: 20.01<br>    },<br>    {<br>      ...<br>      &quot;price&quot;: 15.03<br>    },<br>    ...<br>  ]<br>}</pre><p>Now, look at how broken your shopping cart is 😱 This isn’t some buggy JavaScript behavior, but <strong>a limitation of how we can represent our decimal numbering system with binary machines</strong>. If you do math with floats, you’ll sooner or later encounter those inaccuracies.</p><p>The good news is, <strong>we don’t have to use floats to store money</strong>. That’s exactly where Dinero.js comes into play.</p><h3>Dinero.js, a wrapper for money</h3><p><strong>Dinero.js is to money what Moment.js is to dates.</strong> It’s a library that lets you create monetary <a href="https://en.wikipedia.org/wiki/Value_object">value objects</a>, manipulate them, ask them questions, and format them. It relies on Martin Fowler’s <a href="https://martinfowler.com/eaaCatalog/money.html">money pattern</a> and helps you solve all common problems caused by floats, primarily by storing amounts in minor currency unit, as integers.</p><p>Open up your terminal and install Dinero.js:</p><pre>npm install dinero.js --save</pre><p>Then import it into App.vue:</p><pre>import Dinero from &#39;dinero.js&#39;</pre><pre>export default {<br>  ...<br>}</pre><p>You can now create Dinero objects 🎉</p><pre>// returns a Dinero object with an amount of $50<br>Dinero({ amount: 500, currency: &#39;USD&#39; })</pre><pre>// returns $4,000.00<br>Dinero({ amount: 500 })<br>  .add(Dinero({ amount: 500 }))<br>  .multiply(4)<br>  .toFormat()</pre><p>Let’s create a factory method to turn our price properties into Dinero objects on demand. We have floats with up to two decimal places. This means if we want to turn them into their equivalents in minor currency units (in our case, dollars), <strong>we need to multiply them by 10 to the power of 2</strong>.</p><p>We pass the factor as an argument with a default value, so we can use the method with currencies that have different <a href="https://en.wikipedia.org/wiki/ISO_4217#Treatment_of_minor_currency_units_.28the_.22exponent.22.29">exponents</a>.</p><pre>export default {<br>  ...<br>  methods: {<br>    toPrice(amount, factor = Math.pow(10, 2)) {<br>      return Dinero({ amount: amount * factor })<br>    }<br>  }<br>}</pre><p>Dollars are the default currency, so we don’t need to specify it.</p><p>Because we’re doing floating point math during the conversion, some calculations may end up as slightly inaccurate floats. That’s easy to fix by rounding the result to the closest integer.</p><pre>toPrice(amount, factor = Math.pow(10, 2)) {<br>  return Dinero({ amount: Math.round(amount * factor) })<br>}</pre><p>Now we can use toPrice in our computed properties:</p><pre>export default {<br>  ...<br>  computed: {<br>    getShippingPrice() {<br>      return this.toPrice(this.data.shippingPrice)<br>    },<br>    getSubtotal() {<br>      return this.data.items.reduce(<br>        (a, b) =&gt;<br>          a.add(<br>            this.toPrice(b.price).multiply(b.quantity)<br>          ),<br>        Dinero()<br>      )<br>    },<br>    getTotal() {<br>      return this.getSubtotal.add(this.getShippingPrice)<br>    }<br>  }<br>}</pre><p>And in our template:</p><pre>&lt;ul class=&quot;items&quot;&gt;<br>  &lt;li :key=&quot;item.id&quot; v-for=&quot;item in data.items&quot; class=&quot;item&quot;&gt;<br>    &lt;div class=&quot;item-preview&quot;&gt;<br>      &lt;img :src=&quot;item.thumbnail&quot; :alt=&quot;item.title&quot; class=&quot;item-thumbnail&quot;&gt;<br>      &lt;div&gt;<br>        &lt;h2 class=&quot;item-title&quot;&gt;{{ item.title }}&lt;/h2&gt;<br>        &lt;p class=&quot;item-description&quot;&gt;{{ item.description }}&lt;/p&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;div&gt;<br>      &lt;input type=&quot;text&quot; class=&quot;item-quantity&quot; v-model=&quot;item.quantity&quot;&gt;<br>      &lt;span class=&quot;item-price&quot;&gt;{{ toPrice(item.price) }}&lt;/span&gt;<br>    &lt;/div&gt;<br>  &lt;/li&gt;<br>&lt;/ul&gt;<br>&lt;h3 class=&quot;cart-line&quot;&gt;<br>  Subtotal<br>  &lt;span class=&quot;cart-price&quot;&gt;{{ getSubtotal }}&lt;/span&gt;<br>&lt;/h3&gt;<br>&lt;h3 class=&quot;cart-line&quot;&gt;<br>  Shipping<br>  &lt;span class=&quot;cart-price&quot;&gt;{{ getShippingPrice }}&lt;/span&gt;<br>&lt;/h3&gt;<br>&lt;h3 class=&quot;cart-line&quot;&gt;<br>  Total<br>  &lt;span class=&quot;cart-price cart-total&quot;&gt;{{ getTotal }}&lt;/span&gt;<br>&lt;/h3&gt;</pre><p>If you look at your shopping cart, you’ll see {} in place of prices. That’s because we’re trying to display an object. Instead, <strong>we need to format them so they can display prices with the right syntax</strong>, alongside their currency symbol.</p><p>We can achieve that with Dinero’s <a href="https://sarahdayan.github.io/dinero.js/module-Dinero.html#~toFormat">toFormat method</a>.</p><pre>&lt;ul class=&quot;items&quot;&gt;<br>  &lt;li :key=&quot;item.id&quot; v-for=&quot;item in data.items&quot; class=&quot;item&quot;&gt;<br>    ...<br>    &lt;div&gt;<br>      ...<br>      &lt;span class=&quot;item-price&quot;&gt;<br>        {{ toPrice(item.price).toFormat() }}<br>      &lt;/span&gt;<br>    &lt;/div&gt;<br>  &lt;/li&gt;<br>&lt;/ul&gt;<br>&lt;h3 class=&quot;cart-line&quot;&gt;<br>  Subtotal<br>  &lt;span class=&quot;cart-price&quot;&gt;<br>    {{ getSubtotal.toFormat() }}<br>  &lt;/span&gt;<br>&lt;/h3&gt;<br>&lt;h3 class=&quot;cart-line&quot;&gt;<br>  Shipping<br>  &lt;span class=&quot;cart-price&quot;&gt;<br>    {{ getShippingPrice.toFormat() }}<br>  &lt;/span&gt;<br>&lt;/h3&gt;<br>&lt;h3 class=&quot;cart-line&quot;&gt;<br>  Total<br>  &lt;span class=&quot;cart-price cart-total&quot;&gt;<br>    {{ getTotal.toFormat() }}<br>  &lt;/span&gt;<br>&lt;/h3&gt;</pre><p>Look in your browser: <strong>you now have a well-formatted, fully functional shopping cart</strong> 🤗</p><h3>Going further</h3><p>Now that you have a good grasp of the basics of Dinero.js, time to raise the bar a little.</p><h4>Presentation</h4><p>Let’s change shippingPrice to 0 in the JSON file. Your cart should now display <em>“Shipping: $0.00”</em>, which is accurate but not user-friendly. Wouldn’t it be nicer for it to say <em>“Free”</em>?</p><p>Fortunately, Dinero.js has a plenty of handy methods to ask questions to your instances. In our case, the <a href="https://sarahdayan.github.io/dinero.js/module-Dinero.html#~isZero">isZero method</a> is exactly what we need.</p><p>In the template, you can display text instead of a formatted Dinero object whenever it represents zero:</p><pre>&lt;h3 class=&quot;cart-line&quot;&gt;<br>  Shipping<br>  &lt;span class=&quot;cart-price&quot;&gt;<br>    {{<br>      getShippingPrice.isZero() ?<br>      &#39;Free&#39; :<br>      getShippingPrice.setLocale(getLocale).toFormat()<br>    }}<br>  &lt;/span&gt;<br>&lt;/h3&gt;</pre><p>Of course, you can generalize this behavior by wrapping it in a method. It would take a Dinero object as an argument and return a String. This way, you could show <em>“Free”</em> whenever you try to display a zero amount.</p><h4>Locale switching</h4><p>Imagine you’re making an e-commerce website. You want to accommodate your international audience, so you translate content and add a language switcher. Yet, there’s one detail that may slip your attention: <strong>money formatting also changes depending on the language</strong>. For example, €10.00 in American English translates to 10,00 € in French.</p><p>Dinero.js supports international formatting via the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl">I18n API</a>. This lets you display amounts with localized formatting.</p><p>Dinero.js is immutable, so we can’t rely on changing <a href="https://sarahdayan.github.io/dinero.js/global.html#Globals">Dinero.globalLocale</a> to reformat all existing instances. Instead, we need to use the <a href="https://sarahdayan.github.io/dinero.js/module-Dinero.html#~setLocale">setLocale method</a>.</p><p>First, we add a new property language in data and set it to a default value. For locales, you need to use a <a href="http://tools.ietf.org/html/rfc5646">BCP 47 language tag</a> such as en-US.</p><pre>data() {<br>  return {<br>    data: {<br>      ...<br>    },<br>    language: &#39;en-US&#39;<br>  }<br>}</pre><p>Now we can use setLocale directly on Dinero objects. When language changes, the formatting will change as well.</p><pre>export default {<br>  ...<br>  methods: {<br>    toPrice(amount, factor = Math.pow(10, 2)) {<br>      return Dinero({ amount: Math.round(amount * factor) })<br>        .setLocale(this.language)<br>    }<br>  },<br>  computed: {<br>    ...<br>    getSubtotal() {<br>      return this.data.items.reduce(<br>        (a, b) =&gt;<br>          a.add(<br>            this.toPrice(b.price).multiply(b.quantity)<br>          ),<br>        Dinero().setLocale(this.language)<br>      )<br>    },<br>    ...<br>  }<br>}</pre><p>All we need is to add setLocale in toPrice and getSubtotal, the only places where we’re creating Dinero objects.</p><p>Now we can add our language switcher:</p><pre>// HTML<br>&lt;h1 class=&quot;title&quot;&gt;<br>  Order<br>  &lt;span&gt;<br>    &lt;span class=&quot;language&quot; <a href="http://twitter.com/click">@click</a>=&quot;language = &#39;en-US&#39;&quot;&gt;English&lt;/span&gt;<br>    &lt;span class=&quot;language&quot; <a href="http://twitter.com/click">@click</a>=&quot;language = &#39;fr-FR&#39;&quot;&gt;French&lt;/span&gt;<br>  &lt;/span&gt;<br>&lt;/h1&gt;</pre><pre>// CSS<br>.language {<br>  margin: 0 2px;<br>  font-size: 60%;<br>  color: rgba(#333a45, 0.6);<br>  text-decoration: underline;<br>  cursor: pointer;<br>}</pre><p>When you click on the switcher, it will reassign language, which will change how the objects are formatted. Because the library is immutable, this will return new objects instead of changing existing ones. It means if you create a Dinero object and decide to display it somewhere, then reference it somewhere else and apply a setLocale on it, <strong>your initial instance won’t be affected</strong>. No pesky side effects!</p><h4>All tax included</h4><p>It’s common to see a tax line on shopping carts. You can add one with Dinero.js, using the <a href="https://sarahdayan.github.io/dinero.js/module-Dinero.html#~percentage">percentage method</a>.</p><p>First, let’s add a vatRate property in the JSON file:</p><pre>{<br>  ...<br>  &quot;vatRate&quot;: 20<br>}</pre><p>And an initial value in data:</p><pre>data() {<br>  return {<br>    data: {<br>      ...<br>      vatRate: 0<br>    }<br>  }<br>}</pre><p>Now we can use this value to calculate the total of our cart with tax. First, we need to create a getTaxAmount computed property. We can then add it to getTotal as well.</p><pre>export default {<br>  ...<br>  computed: {<br>    getTaxAmount() {<br>      return this.getSubtotal.percentage(this.data.vatRate)<br>    },<br>    getTotal() {<br>      return this.getSubtotal<br>        .add(this.getTaxAmount)<br>        .add(this.getShippingPrice)<br>    }<br>  }<br>}</pre><p>The shopping cart now shows the total with tax. We can also add a line to show what the tax amount is:</p><pre>&lt;h3 class=&quot;cart-line&quot;&gt;<br>  VAT ({{ data.vatRate }}%)<br>  &lt;span class=&quot;cart-price&quot;&gt;{{ getTaxAmount.toFormat() }}&lt;/span&gt;<br>&lt;/h3&gt;</pre><p>And we’re done! We’ve explored several concepts of Dinero.js, but that’s only scratching the surface of what it has to offer. You can <a href="https://sarahdayan.github.io/dinero.js">read through the documentation</a> and check out the project on <a href="https://github.com/sarahdayan/dinero.js">GitHub</a>. Star it, fork it, send me feedback, or even open a pull request! I have a nice little <a href="https://github.com/sarahdayan/dinero.js/blob/master/CONTRIBUTING.md">contributing guide</a> to help you get started.</p><p>You can also look at the final code on <a href="https://codesandbox.io/s/ojvmp7ryk5">CodeSandbox</a>.</p><p>I’m currently working on bringing a convert method to Dinero.js, as well as better support for all <a href="https://en.wikipedia.org/wiki/ISO_4217">ISO 4217 currencies</a> and cryptos. You can stay tuned by following me on <a href="https://twitter.com/frontstuff_io">Twitter</a>.</p><p>Happy coding! 👩🏻‍💻</p><p><em>Originally published at </em><a href="https://frontstuff.io/build-a-shopping-cart-with-vue-and-dinerojs"><em>frontstuff.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22a7dc4c5352" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/how-to-build-a-shopping-cart-with-vue-and-dinero-js-22a7dc4c5352">How to build a shopping cart with Vue and Dinero.js</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to handle monetary values in JavaScript]]></title>
            <link>https://medium.com/free-code-camp/how-to-handle-monetary-values-in-javascript-3fef5eeb3eda?source=rss-20bd5f22250b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fef5eeb3eda</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Sarah Dayan]]></dc:creator>
            <pubDate>Thu, 19 Apr 2018 17:00:32 GMT</pubDate>
            <atom:updated>2018-04-21T15:33:53.957Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q76Xol7zRdld3s-BbFrB_Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/gbQ3EsFSdG8?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Thought Catalog</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Money is everywhere.</p><p>Banking apps, e-commerce websites, stock exchange platforms — we interact with money daily. We also increasingly rely on technology to handle ours.</p><p>Yet, there’s no consensus around how to programmatically handle monetary values. It’s a prevalent concept in modern societies, yet it’s not a first-class data type in any mainstream language, while things like date and time are. As a result, <strong>every piece of software comes up with its own way of handling money, with all the pitfalls that come with it</strong>.</p><h4>Pitfall #1: Money as a Number</h4><p>Your first instinct when you need to represent money might be to use a Number.</p><p>Money is nothing more than a numeric value, right? Wrong.</p><p>The amount part of a monetary value is only relative to another aspect: its currency. There’s no such thing as 10 “money.” It’s 10 dollars, 10 euros, 10 bitcoins… If you want to add two monetary values with different currencies, you need to convert them first. Same if you want to compare them: if all you have is an amount, you can’t make an accurate comparison. <strong>Amount and currency can’t go without one another</strong>.</p><h4>Pitfall #2: Floating point math</h4><p>Most contemporary currencies are either decimal or have no sub-units at all. This means that when money has sub-units, the number of these in a main unit is a power of 10. For example, there are 100 cents in a dollar, being 10 to the power of 2.</p><p>Using a decimal system has advantages, but raises a major issue when it comes to programming. Computers use a binary system, so <a href="http://0.30000000000000004.com/">they can’t natively represent decimal numbers</a>. Some languages have come up with their own solutions like the <a href="https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html">BigDecimal</a> type in Java or the <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/decimal">decimal</a> type in C#. JavaScript only has the Number type, which can be used as an integer or a <a href="https://en.wikipedia.org/wiki/IEEE_754">double precision float</a>. Because it’s a binary representation of a base 10 system, <strong>you end up with inaccurate results when you try to do math</strong>.</p><pre>0.1 + 0.2 // returns 0.30000000000000004 😧</pre><p><strong>Using floats to store monetary values is a bad idea</strong>.</p><p>As you calculate more values, the imperceptible precision errors lead to larger gaps. This inevitably ends up causing rounding issues.</p><h4>Pitfall #3: Percentage vs. allocation</h4><p>Sometimes you need to split money, but <strong>percentages can’t cut it without adding or losing pennies</strong>.</p><p>Imagine you need to bill $999.99 with a 50% downpayment. This can be done with some simple math. Half is $499.995, but you can’t split a penny so you’ll likely round the result to $500. Problem is, as you charge the second half, you end up with the same result and charge a penny extra.</p><p>You can’t solely rely on percentages or divisions to split money because <strong>it’s not divisible to infinity</strong>. Gas price may show more than two fraction digits, but it’s only symbolic: you always end up paying a rounded price.</p><h4>Engineering to the rescue</h4><p>As you can see, there is much more to money than meets the eye, and it’s more than simple Number data types can take.</p><p>Fortunately, <strong>software engineer </strong><a href="https://martinfowler.com/"><strong>Martin Fowler</strong></a><strong> came up with a solution</strong>. In <a href="https://martinfowler.com/books/eaa.html"><em>Patterns of Enterprise Application Architecture</em></a>, he describes <a href="https://martinfowler.com/eaaCatalog/money.html">a pattern for monetary values</a>:</p><h4>Properties</h4><p>Methods</p><ul><li>Math: add, subtract, multiply, allocate</li><li>Comparison: equals to, greater than, greater than or equal, lesser than, lesser than or equal.</li></ul><p><strong>From this, you can create value objects that fulfill most of your monetary needs</strong>.</p><h4>Money as a data structure</h4><p>Money behaves differently from a simple number, and thus should be treated differently. The first and most important thing is that <strong>it should always be composed of an amount and a currency</strong>.</p><p>You can do everything from an amount and a currency. You can add monetary amounts together, check if they’re equal or not, and format them into whatever you need. This can be done through an object’s methods. <strong>In JavaScript, any kind of function that returns an object will do the trick</strong>.</p><h4>Amounts in cents</h4><p>There are several ways you can solve the floating point issue in JavaScript.</p><p>You can use libraries like <a href="https://mikemcl.github.io/decimal.js">Decimal.js</a> that will handle your floats as strings. This isn’t a bad solution, and even comes in handy when you have to handle <a href="https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Number/MAX_SAFE_INTEGER">big numbers</a>. <strong>Yet, it comes at the expense of adding a (heavy) dependency, resulting in slower performance</strong>.</p><p>You can multiply floats into integers before you calculate, then divide them back.</p><pre>(0.2 * 100 + 0.01 * 100) / 100 // returns 0.21 🎉</pre><p>It’s a fine solution, but requires extra calculations either on object construction or on each manipulation. This isn’t necessarily draining on performance, but is still more process work than necessary.</p><p>A third alternative is to directly store values in cents, relative to the unit. If you need to store 10 cents, you won’t store 0.1, but 10. This allows you to work with integers only, which means safe calculations (until you hit <a href="https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Number/MAX_SAFE_INTEGER">big numbers</a>) and great performance.</p><h4>Dinero.js, an immutable library to create, calculate, and format monetary values</h4><p>From these observations, I made a JavaScript library: <a href="https://github.com/sarahdayan/dinero.js"><strong>Dinero.js</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cen7L63Ka4n0WA5T.png" /></figure><p>Dinero.js follows Fowler’s pattern and more. It lets you create, calculate, and format monetary values in JavaScript. You can do math, parse and format your objects, ask them questions, and make your development process easier.</p><p>The library was designed to be immutable and chainable. It supports global settings, has extended formatting options, and provides native internationalization support.</p><h4>Why immutable?</h4><p>An immutable library is safer and more predictable. Mutable operations and reference copies are the sources of many bugs. Opting for immutability avoids them altogether.</p><p>With Dinero.js, you can perform calculations without worrying about altering original instances. In the following Vue.js example, price won’t be altered when priceWithTax is called. If the instance was mutable, it would.</p><pre>const vm = new Vue({<br>  data: {<br>    price: Dinero({ amount: 500 })<br>  },<br>  computed: {<br>    priceWithTax() {<br>      return this.price.add(this.price.percentage(10))<br>    }<br>  }<br>})</pre><h4>Chainability</h4><p>Good developers strive to make their code more concise and easier to read. When you want to successively perform several operations on a single object, chaining provides an elegant notation and concise syntax.</p><pre>Dinero({ amount: 500 })<br>  .add(Dinero({ amount: 200 }))<br>  .multiply(4)<br>  .setLocale(&#39;fr-FR&#39;)<br>  .toFormat() // returns &quot;28,00 US$&quot;</pre><h4>Global settings</h4><p>When you’re handling lots of monetary values, chances are you want some of them to share some attributes. If you’re making a website in German, you’ll likely want to show amounts with the German currency format.</p><p>This is where global settings come in handy. Instead of passing them to every instance, you can declare options that will apply to all new objects.</p><pre>Dinero.globalLocale = &#39;de-DE&#39;<br>Dinero({ amount: 500 }).toFormat() // returns &quot;5,00 $&quot;</pre><h4>Native Internationalization support</h4><p>Traditionally, libraries use locale files for internationalization. If you’re exhaustive, they tend to make libraries much heavier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*C5q7okNXFZ0FD5Op.png" /><figcaption>Moment.js is four times heavier with locale files.</figcaption></figure><p>Locale files are also hard to maintain. The Internationalization API is native and <a href="https://caniuse.com/#feat=internationalization">pretty well supported</a>. Unless you have to work with outdated and/or marginal browsers, toFormat is safe to use.</p><h4>Formatting</h4><p>An object is great to store data, but not so helpful when it comes to displaying it. Dinero.js comes with various formatting methods, including toFormat. It provides intuitive and concise syntactic sugar over Number.prototype.toLocaleString. Pair it with setLocale and you’ll be able to display any Dinero object into the proper format, in any language. This is particularly helpful for multi-lingual e-commerce websites.</p><h4>What’s next?</h4><p>Fowler’s money pattern is widely recognized as a great solution. It has inspired many implementations in many languages. If you’re into DIY, I recommend it and the observations from this article as a starting point. Or you can pick <a href="https://github.com/sarahdayan/dinero.js">Dinero.js</a>: a modern, reliable, fully tested solution that already works.</p><p>Have fun!</p><p><em>Any questions about Dinero.js? Or on how to make your own money data structure? Let’s chat on </em><a href="https://twitter.com/frontstuff_io"><em>Twitter</em></a><em>!</em></p><p><em>Originally published at </em><a href="https://frontstuff.io/how-to-handle-monetary-values-in-javascript"><em>frontstuff.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fef5eeb3eda" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/how-to-handle-monetary-values-in-javascript-3fef5eeb3eda">How to handle monetary values in JavaScript</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to automate your open source JavaScript project’s most repetitive tasks]]></title>
            <link>https://medium.com/free-code-camp/how-to-setup-productivity-tools-for-an-open-source-javascript-project-c52d403c5087?source=rss-20bd5f22250b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c52d403c5087</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[life-lessons]]></category>
            <dc:creator><![CDATA[Sarah Dayan]]></dc:creator>
            <pubDate>Mon, 09 Apr 2018 03:44:13 GMT</pubDate>
            <atom:updated>2018-04-09T03:47:35.848Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4x8Zuht2TaQ87ZhwYcLUqQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@cakirchoff">Chad Kirchoff</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>When I started my career, my mentor told me:</p><blockquote>“A good developer is a lazy developer. Don’t waste time on repetitive tasks, instead spend it on building automated processes. The computer works for you, and it will always be faster than you.”</blockquote><p>This was back in 2010, and the toolset we had at our disposal was more scarce than it is today. Yet, this piece of advice has stuck with me ever since.</p><p>From executable scripts to Yeoman configs, IFTTT setups and Automator workflows, not to mention the slew of apps I use to assist my every move on the computer. I see automation as a game and take a lot of satisfaction in it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/0*UnKYnRP5pdyPZZq7.gif" /></figure><p>JavaScript has exploded since then, and has grown in complexity. We used to add an external JavaScript file to an HTML page and call it a day. But there’s much more to building a web project now than just coding. We also have more tools than we can use to unload repetitive tasks, so finding your way through it all can be overwhelming.</p><p>To sort this out, I decided to show you the detailed setup for a real-life project- my latest open source project, <a href="https://github.com/sarahdayan/dinero.js">Dinero.js</a>.</p><p><strong>Disclaimer:</strong> This isn’t a tutorial on how to make an open source library, but rather an overview of what I use, how, and why. For a thorough step-by-step guide, I recommend the egghead.io course <a href="https://egghead.io/courses/how-to-write-an-open-source-javascript-library">How to Write an Open Source JavaScript Library</a> by Kent C. Dodds.</p><h3>Dependency management</h3><h4>npm and Yarn</h4><p>Before the modern times, we used to download dependencies by hand and load them globally in pages. This made things easy but led to a number of problems like duplicate libraries, heavy repositories, difficult version management.</p><p>Fortunately, we now have a robust and trust-worthy front-end dependency manager: <a href="http://npmjs.com/">npm</a>. If you come from PHP, you can see npm like Composer and Packagist put together. It provides the richest front-end repository out there, and a great command-line interface to handle dependencies.</p><p>Many people (including me) prefer using <a href="https://yarnpkg.com/">Yarn</a> though: a faster CLI that integrates a powerful cache system, parallelize downloads and provides an offline mode. Now Yarn is <em>only</em> a layer on top of the npm repository: it browses npm packages, but allows you to use their tool instead.</p><h3>Coding style and conventions</h3><h4>EditorConfig</h4><p>Imagine you’re working on several projects, all of which have different conventions. On this library you chose two-space indentation, but this other open source project you contribute to prefers four-space long tabs. Are you going to manually reconfigure your editor every time you switch?</p><p><a href="http://editorconfig.org/">EditorConfig</a> is a configuration file that lives in your project and defines editor settings. Every time you work on a project that has an .editorconfig file, your editor will conform to its rules.</p><p>Most editors can parse .editorconfig files, but if it’s not the case for yours you can still <a href="http://editorconfig.org/#download">download a plugin</a>.</p><h4>Prettier</h4><p>One of the tools I am most grateful for is <a href="https://prettier.io/">Prettier</a>. I dig it so much that I have it as an npm script in my project and as a code editor plugin. That’s how deep my love is.</p><p>Prettier solves the problem of arguing over coding style and wasting time in code review. No more heated discussions around simple vs. double quotes. No more rejected Pull Requests because you forgot a space before an if parenthesis.</p><p>And above all things, no more wasted time formatting code by hand. Prettier is opinionated, so you’ll get limited room for customizing the default rules. And <strong>that’s for the best</strong>: that’s not what you should spend your precious time on.</p><h4>ESLint</h4><p>Like with grammar and spelling, your code isn’t immune to typos. Also, it’s not unlikely to accidentally add code that may introduce bugs, like globals or unwanted type coercion.</p><p>This is what <a href="http://eslint.org/">ESLint</a> takes care of. It will not rewrite your file like Prettier does, but you’ll get warnings in the terminal.</p><p>There <em>is</em> some <a href="https://prettier.io/docs/en/comparison.html">common territory between ESLint and Prettier</a>, which is why I recommend that:</p><ol><li>You run Prettier first, then ESLint.</li><li>You use a tool that ensures they don’t conflict with one another, like <a href="https://github.com/prettier/eslint-config-prettier">eslint-config-prettier</a>.</li></ol><h4>Commitizen and cz-conventional-changelog</h4><p>You’re probably starting to see a pattern here: yes, <strong>I’m big into conventions</strong>. I’d rather trust a convention and focus on my job than fall into the rabbit hole of <a href="https://en.wiktionary.org/wiki/bikeshedding">bikeshedding</a>, and commit messages fall under that category. Now the idea behind conventional commit messages isn’t <em>only</em> to make pretty commits, it’s about automating a large part of your CI workflow.</p><p>When you maintain software, there are some tedious tasks that need to be taken care of. Among them are <strong>keeping a changelog up to date</strong> and <strong>versioning the project</strong>.</p><p>Maintaining a changelog by hand is a pain. You have to check every commit since the latest release, filter out what doesn’t concern the user (changes to the build system, non-breaking refactors), find out what effective changes were made and write it down in a human-readable way.</p><p>Same goes for the version.</p><p>Depending on the changes, you need to resolve what the next version is. No matter how well you think you know <a href="https://frontstuff.io/setup-for-an-open-source-javascript-project#semantic-release">semver</a>, it can be tedious to increment the version by hand. Human error easily leads to incorrect versions, and this can be a big problem for users.</p><p>This is what <a href="https://github.com/commitizen/cz-cli">Commitizen</a> and <a href="https://github.com/commitizen/cz-conventional-changelog">cz-conventional-changelog</a> take off your plate. Instead of committing the usual way, you run a script that asks you questions. It will then commit for you with a properly formatted message that follows the <a href="https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#-git-commit-guidelines">Angular Git Commit Guidelines</a>. Later on, when you deploy with <a href="https://frontstuff.io/setup-for-an-open-source-javascript-project#semantic-release">semantic-release</a>, those commit messages will be used to generate the changelog and resolve the new version number. Automatically. Nice, right?</p><h4>lint-staged</h4><p>If you’re working in a team, one of the best ways to ensure code quality is doing <strong>code reviews</strong>. It’s paramount that code going to production goes under at least a second pair of eyes.</p><p>Now because they’re time-consuming, it’s important that code reviews observe a few rules. Among those, <strong>review time shouldn’t be used to spot linting errors</strong>.</p><p>All formatting and linting should happen before committing. It shouldn’t distract the reviewer from doing their job, and it shouldn’t break the build. This is why <a href="https://github.com/okonet/lint-staged">lint-staged</a> is so useful: every time you commit, it will act as a pre-commit hook and run a script of your choosing.</p><p>In Dinero.js, here’s what my lint-staged configuration looks like:</p><pre>{<br>  &quot;lint-staged&quot;:<br>    { &quot;*.js&quot;: [&quot;npm run lint!&quot;, &quot;git add&quot;]<br>  }<br>}</pre><p>The npm run lint! command sequentially triggers two other scripts: npm run format (Prettier), then npm run lint (ESLint). Every time I try to commit a JavaScript file, Prettier will reformat it. Then, ESLint will perform a scan: if it passes, the commit will go through. Otherwise, ESLint will throw an error and the commit will be aborted.</p><h3>Documentation</h3><h4>JSDoc</h4><p>Documentation should live as close as possible from the code it describes. This is a good way to keep it up to date and guarantee its exhaustiveness. A great implementation of this idea is <strong>doc blocking</strong>: using formatted comments to document code, which can then automatically generate a documentation website. In JavaScript, the most popular documentation generator is <a href="http://usejsdoc.org/">JSDoc</a>.</p><p>With JSDoc, all you need to do is add a comment with specific tags and descriptions above every significative part of the code (a function, a module, etc.)</p><pre>{<br>  /**<br>   * Returns the currency.<br>   *<br>   * @example<br>   * // returns &#39;EUR&#39;<br>   * Dinero({ currency: &#39;EUR&#39; }).getCurrency()<br>   *<br>   * @return {String}<br>   */<br>  getCurrency() {<br>    return currency<br>  }<br>}</pre><p><em>This doc block has a description, one example and a typed return value.</em></p><p>Once written, doc blocks can be turned into a documentation website with a single command. You can use any pre-existing JSDoc template to generate your website or create yours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/0*KnCAfDiyTmqMIq-1.png" /><figcaption>Here’s how the doc block for Dinero.getCurrency looks like once compiled into a website.</figcaption></figure><h4>Why not ESDoc?</h4><p>The younger kid on the block, <a href="https://esdoc.org/">ESDoc</a>, takes a different approach than JSDoc. Among other things, ESDoc was designed to work well with ES6 classes, and concrete code in general. The downside is that <a href="https://github.com/esdoc/esdoc/issues/300">it doesn’t support factory functions</a>.</p><p>Factory functions are dynamic object generators, a behavior that ESDoc doesn’t cover. If you try to document a factory with ESDoc, the generated documentation will come back empty.</p><p>In my case, factories are the building blocks of Dinero.js, which explains my choice.</p><p>If your project uses the ES6 class syntax, ESDoc will meet all your needs. Else, go with JSDoc: it supports all ES6 features, as well as “older” patterns like factory functions and the original syntax for constructors.</p><h4>Algolia DocSearch</h4><p>You may have written your documentation with care and presented it in a pretty website, at the end of the day, what matters is for users to find what they need as quickly as possible. Nobody likes to break their flow for too long to go find something they need. It’s no surprise StackOverflow is so popular: people need answers to their questions, and they need it <em>fast</em>.</p><p><a href="http://algolia.com/">Algolia</a> is the best search service out there. Their (free) <a href="https://community.algolia.com/docsearch">DocSearch</a> solution lets you create an excellent documentation experience for your users. DocSearch is an on-demand service: once your docs are ready, send them a URL and you’ll get a code snippet to add to your website.</p><h3>Tests</h3><h4>Mocha and Chai</h4><p>Unit testing is crucial. If you can only do <strong>one</strong> thing for code quality, forget linting, forget formatting, forget code reviews and <strong>write unit tests</strong>.</p><p>Unit testing forces you to build modular, single-responsibility code and ensures you don’t break things that used to work fine. It’s a crucial part of continuous integration. If you’re serious about what you’re building, you should 100% unit test it.</p><p>Now if you’re just starting out, unit testing may seem a bit scary. The good news is they don’t have to be: thanks to tools like <a href="http://mochajs.org/">Mocha</a> and <a href="http://chaijs.com/">Chai</a>, writing tests comes really close to being <em>fun</em>.</p><p>Here’s an excerpt from my unit tests for Dinero.js:</p><pre>import chai from &#39;chai&#39;<br>import Dinero from &#39;../../src/dinero&#39;</pre><pre>const expect = chai.expect</pre><pre>describe(&#39;Dinero&#39;, () =&gt; {<br>  describe(&#39;#getAmount()&#39;, () =&gt; {<br>    it(&#39;should return the right amount as a number&#39;, () =&gt; {<br>      expect(Dinero({ amount: 500 }).getAmount()).to.equal(500)<br>    })<br>    it(&#39;should return the default amount as a number when no amount is specified&#39;, () =&gt; {<br>      expect(Dinero().getAmount()).to.equal(0)<br>    })<br>  })<br>})</pre><p>This JavaScript file, called a “spec”, uses the Mocha framework and the Chai assertion library. The public API is built to look like actual English sentences: even non-technical people can read the spec files and understand what’s going on. This makes it easy for new contributors, because the learning curve is almost non-existent.</p><p>Tests using Mocha and Chai are natively run with Node.js, which means it expects CommonJS modules for the spec and source files. But thanks to Babel, we don’t have to write CJS if we don’t want to: we can still use ES modules and transpile them on the fly as we run tests! This is how I’m able to include modules with import instead of require and still have fully working tests.</p><h4>Istanbul and Coveralls</h4><p>Writing unit tests is great, but as your project scales, you may lose track of what needs to be tested. It’s not your fault: you’re busy building something and there are a lot of things to remember. That’s why we automate tasks, to assist ourselves and help us remember things we forget. Code coverage monitors your code on a regular basis (usually every time you run tests) and gives you a report of the amount of code that’s covered by unit tests.</p><p><a href="https://istanbul.js.org/">Istanbul</a> is a code coverage tool. In Dinero.js I use <a href="https://github.com/istanbuljs/nyc">nyc</a>, its command-line interface, to generate reports.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/0*bQyzMvC3jdltcCHX.png" /><figcaption>An Istanbul report once unit tests are done.</figcaption></figure><p>Istanbul generates reports in all kinds of formats: terminal output, HTML, but also <a href="http://ltp.sourceforge.net/coverage/lcov.php">LCOV</a>. This one is particularly useful when used with online services like <a href="https://coveralls.io/">Coveralls</a>. Every time <a href="https://frontstuff.io/setup-for-an-open-source-javascript-project#travis-ci">Travis CI</a> runs a build, it executes tests and nyc generates an LCOV file. It’s then sent to Coveralls which generates detailed stats. This is particularly useful for contributions: when someone submits a pull request, a Coveralls bot automatically replies with the updated coverage. This contributes to making code reviews easier and quicker.</p><h3>Build</h3><h4>Babel</h4><p>ES6+ has brought amazing features to JavaScript, but they’re still <a href="https://kangax.github.io/compat-table/es6">not supported everywhere</a>. This doesn’t mean you must wait before you can start to use it: meet <a href="https://babeljs.io/">Babel</a>.</p><p>Babel is a <em>transpiler</em>. It translates code into another language or another <em>version</em> of the same language. Your source code remains the same, but what the user gets is translated into another syntax to ensure it works in their environment. You get to use cutting-edge features, neat syntaxes and keep your source code clean, and you don’t have to worry about it working on old browsers.</p><p>I’ve written the entire Dinero.js source code using ES6 features, such as fat arrow functions and ES modules. Every time I release a version, Babel transpiles the source files into distributable ES5 code.</p><p>Babel also comes handy for unit testing. I’m using Node.js for that, which doesn’t natively support ES modules yet, thus can’t handle my source files. Thanks to Babel, I can transpile them on the fly every time I run my test command.</p><h4>Rollup</h4><p>Once your library is ready, you need to package it so it can be used by different people in different environments. Some will use it with Node. Some will need it directly in the browser as a script tag. Others will want it as an ES module to be included it in their own project and bundled with their own tools.</p><p><a href="https://rollupjs.org/">Rollup</a> is a module bundler like Webpack or Parcel, but it’s particularly useful for building JavaScript libraries. It was designed to work with ES modules, and turn them into any module format you want.</p><p>Back in the days, the code we wrote was exactly the code that ended up in production. If you wanted your code to be as ubiquitous as possible, you’d wrap it into a <a href="https://github.com/umdjs/umd">UMD</a> pattern by hand. Today, you can code exactly the way you want and ship different bundles for everyone, thanks to module bundlers like Rollup. Need a UMD version? There you go. Along with an <a href="http://requirejs.org/docs/whyamd.html#amd">AMD</a>, a <a href="https://nodejs.org/docs/latest/api/modules.html">CJS</a>, an <a href="https://developer.mozilla.org/docs/Glossary/IIFE">IIFE</a>, anything.</p><h3>CI</h3><h4>GitHub</h4><p>The most popular collaborative open source platform needs no introduction. <a href="https://github.com/">GitHub</a> is a wonderful product that fulfills everything developers can hope for and beyond. It hosts most of my projects. It hosts this blog. It connects with the best CI tools on the market. If you want to contribute to your favorite open source projects, build yourself a reputation and create the next best tools for other developers, look no further.</p><h4>Travis CI</h4><p>You can look at <a href="http://travis-ci.org/">Travis CI</a> as the conductor of your project’s build process.</p><p>Crafting a quality project is hard, and coding is only a small part of it. There are tasks to run in a certain order, at the right time, under the right circumstances. Here’s a list of all that needs to be done once I want to ship anything for Dinero.js:</p><p>Run unit tests. <strong>If they pass</strong>:</p><ul><li>Run code coverage</li><li>Build a version (dist files)</li><li>Recompile the docs</li><li>Tag a version and push the tag on GitHub</li><li>Increment the version and push the build to npm</li><li>Write an entry in the changelog</li><li>Push the docs files to GitHub Pages</li></ul><p><strong>Otherwise</strong>, fix things, rinse and repeat.</p><p>Before I installed my CI pipeline, I tried doing this by hand. Guess what? There hasn’t been <em>a single time</em> when I did it right. Why? Because as a typical human, I’m error-prone and subject to distractions. On the other hand, machines respond well to orders. They will do exactly what you want, how you want it. All you have to do is specify it well, <em>once</em>.</p><p>Travis CI is free for open-source projects and integrates well with third-party services. All you have to do is log in with your GitHub account and sync a project. By default, Travis will execute tests every time you push to your remote repository. Then, you can <a href="https://docs.travis-ci.com/user/customizing-the-build">tell Travis what to do</a> when tests pass with a .travis.yml file at the root of the project.</p><h4>semantic-release</h4><p>Before getting into what semantic-release does, you need to understand <a href="https://semver.org/">Semantic Versioning</a> (aka “semver”).</p><p>In short, semver is a convention based on an X.Y.Z numeric format, respectively the MAJOR, the MINOR and the PATCH:</p><ul><li>When you fix a bug but your changes are backwards compatible, you increment the PATCH.</li><li>When you add a feature but your changes are still backwards compatible, you increment the MINOR.</li><li>When you make any kind of backwards incompatible changes, you increment the MAJOR.</li></ul><p>This helps people who depend on your project know if they can safely upgrade, and simplifies dependency management in general.</p><p>Semantic Versioning is widely used in software development, but it can be hard to enforce. Again, we humans are error-prone and sentimental creatures. If you forget to take a commit into account, have a doubt on the nature of a change, or simply don’t understand semver quite yet, you can mislabel a new version. If you fix a small bug that slipped your attention just after releasing a new version, you might be tempted to sneak it in and act like nothing happened. This is where <a href="https://github.com/semantic-release">semantic-release</a> comes into play.</p><p>In short, semantic-release <strong>takes care of versioning for you</strong>. You have no say in it. It uses your <a href="https://frontstuff.io/setup-for-an-open-source-javascript-project#commitizen--cz-conventional-changelog">conventionally written commit messages</a> to decide what the next version will be. Add it to your CI pipeline (in your <a href="https://frontstuff.io/setup-for-an-open-source-javascript-project#travis-ci">Travis CI</a> workflow, for example), and you get a fully automated system that will read your commits, change the version, tag it, push to GitHub, push to npm, and write your changelog. Phew.</p><h3>Isn’t it a bit much?</h3><p>This may look like a lot of things to set up. <em>“Do I really need all this?”</em> you may wonder. I’ll reply with a few questions: how many tasks are you currently handling by hand? How much time does a release take you? How confident are you when you do it? When was the last time you performed your entire workflow without forgetting anything?</p><p>I personally can’t deploy a release by hand without a cheat sheet. Linting, formatting, testing, code coverage, docs, building, semantic versioning, releasing, updating the changelog, all in that order while making sure I’m on the right branch… ugh. Really hope I didn’t leave a typo! This process is so time-consuming, you can screw it up in so many ways, and it’s repeatedly taking you so much time from actual work, that <strong>automating it should be a no-brainer</strong>.</p><p>It looks tricky when you’re not used to it, but once you’ve built your workflow, all you have to do is maintain it. Update dependencies, keep an eye on innovative new tools, improve the process. You can even use a scaffolding tool to save your whole configuration and deploy ready-to-use project templates. Give it a try!</p><p>What about you? What’s your workflow for web projects? What has made your life easier? Come chat with me about it on <a href="https://twitter.com/frontstuff_io">Twitter</a>!</p><p>Also, you can check out more of my articles on <a href="https://frontstuff.io/setup-for-an-open-source-javascript-project">my blog</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c52d403c5087" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/how-to-setup-productivity-tools-for-an-open-source-javascript-project-c52d403c5087">How to automate your open source JavaScript project’s most repetitive tasks</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to generate all your utility classes with Sass Maps]]></title>
            <link>https://medium.com/free-code-camp/how-to-generate-all-your-utility-classes-with-sass-maps-8921ab3b4508?source=rss-20bd5f22250b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8921ab3b4508</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sarah Dayan]]></dc:creator>
            <pubDate>Thu, 01 Mar 2018 17:14:28 GMT</pubDate>
            <atom:updated>2018-03-01T17:14:28.181Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*HJAnPhGEMFf-pqxuuW8yyw.jpeg" /><figcaption>Photo by <a href="https://www.flickr.com/photos/59632563@N04/">Vic</a> on <a href="https://www.flickr.com/photos/59632563@N04/6645629155">Flickr</a></figcaption></figure><p>One of the powers of utility classes lies in giving you access to every small concept of your design system in a slew of contexts. If your main color is royal blue, you can apply it as a text color on anything with a .text-royal-blue class, as a background color with a .bg-royal-blue class, and so on.</p><p>But how do you write them in an effective, consistent, and scalable way?</p><p><strong><em>TL;DR</em></strong><em>: this post goes in-depth in the how-to stuff. If you want to understand the whole thought process, read on. Otherwise you can grab the code on </em><a href="https://gist.github.com/sarahdayan/4d2cc04a636e8039f10a889a0e29fbd9"><em>GitHub</em></a><em> or test it out on </em><a href="https://www.sassmeister.com/gist/4d2cc04a636e8039f10a889a0e29fbd9"><em>SassMeister</em></a><em>.</em></p><pre>$royal-blue: #0007ff;</pre><pre>.text-royal-blue {<br>  color: $royal-blue;<br>}</pre><pre>.bg-royal-blue {<br>  background: $royal-blue;<br>}</pre><pre>...</pre><p>That’s repetitive. Not only are you hand-typing the color name and value every single time, but you’re also creating an unmaintainable system. What happens when you have ten color utilities like these, and you need to add one more color to the scheme?</p><p>You shouldn’t spend time on mindless, tedious tasks. <strong>That’s what scripting languages are for</strong>. If you’re already using Sass, you need to harness its power and let it help you.</p><h3>What are Sass Maps?</h3><p><a href="http://sass-lang.com/documentation/file.SASS_REFERENCE.html#Maps">Maps</a> are a Sass data type that represent <strong>an association between keys and values</strong>. If you’re familiar with other scripting languages, you could see it as an <a href="https://en.wikipedia.org/wiki/Associative_array">associative array</a>. It allows you to store data, and have a name to reference each piece.</p><p><a href="http://sass-lang.com/documentation/file.SASS_REFERENCE.html#Lists">Lists</a> and maps are a bit similar, in that they’re both storing a collection of data and they’re both iterable in an @each loop. But unlike lists, maps make it easy to reference any piece of information by calling it by its name. This makes it ideal for grouping logically related information.</p><pre>$colors: (<br>  mako-grey: #404145,<br>  fuel-yellow: #ecaf2d,<br>  pastel-green: #5ad864<br>);</pre><h3>Let’s add some logic</h3><p>Now that our colors are neatly stored inside a map, we need to iterate it to generate our utility classes. To do that, we’ll use the @each directive inside a @mixin that we’ll include later in our utility base class.</p><pre>@mixin color-modifiers {<br>  // do stuff<br>}</pre><p>Let’s now use the @each directive to loop through $colors and fetch the right data.</p><pre>@mixin color-modifiers {<br>  @each $name, $hex in $colors {<br>    // do stuff<br>  }<br>}</pre><p>We’re iterating $colors and at every loop, the current key will be referenced in $name and the color’s hexadecimal code will be in $hex. We can start building our ruleset.</p><pre>@mixin color-modifiers {<br>  @each $name, $hex in $colors {<br>    &amp;-#{$name} {<br>      color: $hex;<br>    }<br>  }<br>}</pre><p>Now for every pair in the map, @each will generate a ruleset that references the parent selector with the &amp; character, appends a hyphen and the color’s name, and sets the color attribute to the current hexadecimal value.</p><p>In other words, doing this:</p><pre>.text {<br>  @include color-modifiers;<br>}</pre><p>Will generate this:</p><pre>.text-mako-grey {<br>  color: #404145;<br>}<br>.text-fuel-yellow {<br>  color: #ecaf2d;<br>}<br>.text-pastel-green {<br>  color: #5ad864;<br>}</pre><p>Pretty neat, uh? Actually, we barely scratched the surface. For now, our mixin can only output rules with the color attribute. What if we want to create some utility classes for background colors?</p><p>Fortunately, Sass allows us to pass arguments to mixins.</p><pre>@mixin color-modifiers($attribute: &#39;color&#39;) {<br>  @each $name, $hex in $colors {<br>    &amp;-#{$name} {<br>      #{$attribute}: $hex;<br>    }<br>  }<br>}</pre><p>Now we can specify exactly what attribute we want.</p><p>Let’s improve our mixin a little more: right now, the modifier prefix is a hardcoded hyphen. This means your classes will always be in the form of .base-modifier. What if you need it to change? What if you also want to generate some BEM-flavored modifiers (two hyphens)? Again, that’s something we can achieve by using arguments.</p><pre>@mixin color-modifiers($attribute: &#39;color&#39;, $prefix: &#39;-&#39;) {<br>  @each $name, $hex in $colors {<br>    &amp;#{$prefix}#{$name} {<br>      #{$attribute}: $hex;<br>    }<br>  }<br>}</pre><p>Now we can generate modifier classes with any kind of prefix we want. So, doing this:</p><pre>.text {<br>  @include color-modifiers($prefix: &#39;--&#39;);<br>}</pre><p>Will generate this:</p><pre>.text--mako-grey {<br>  color: #404145;<br>}<br>.text--fuel-yellow {<br>  color: #ecaf2d;<br>}<br>.text--pastel-green {<br>  color: #5ad864;<br>}</pre><p><strong>Pro tip</strong>: in Sass, you can explicitly name arguments when you call a mixin or a function (like in the example above). This avoids having to provide them in order.</p><h3>Maps within maps</h3><p>I like to use a slightly different color system so I can manage tonal variations. By nesting maps within maps, I have a clean and readable way to keep shades grouped together.</p><pre>$colors: (<br>  grey: (<br>    base: #404145,<br>    light: #c7c7cd<br>  ),<br>  yellow: (<br>    base: #ecaf2d<br>  ),<br>  green: (<br>    base: #5ad864<br>  )<br>);</pre><p>If we want to work with such a color system, we need to adapt our mixin so it goes iterating a level deeper.</p><pre>@mixin color-modifiers($attribute: &#39;color&#39;, $prefix: &#39;-&#39;, $separator: &#39;-&#39;) {<br>  @each $name, $color in $colors {<br>    &amp;#{$prefix}#{$name} {<br>      @each $tone, $hex in $color {<br>        &amp;#{$separator}#{$tone} {<br>          #{$attribute}: $hex;<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>We added a new argument, $separator, to link the color’s name and the tone. We could have used the $prefix but it doesn’t have the same purpose. Using a dedicated variable with a default value is a better choice, as it gives us full freedom when we use the mixin.</p><p>Now, doing this:</p><pre>.text {<br>  @include color-modifiers;<br>}</pre><p>Will generate this:</p><pre>.text-grey-base {<br>  color: #404145;<br>}<br>.text-grey-light {<br>  color: #c7c7cd;<br>}<br>.text-yellow-base {<br>  color: #ecaf2d;<br>}<br>.text-green-base {<br>  color: #5ad864;<br>}</pre><p>Great! We now have helpers composed of a base class, a color, and a tone. One thing we need to improve, though, is how base color modifiers are outputted. We actually don’t need that -base suffix — the base class and color are enough.</p><p>What we must do is check for the tone in the nested @each loop, and only output it and the $separator when it’s not “base.” Luckily for us, Sass already has everything we need.</p><h3>@if, @else, if()</h3><p>Our first instinct might be to use the @if/@else directives. Problem is, this would force us to repeat code and will result in complicated code. Instead, we’re going to use one of Sass’ secret weapons: if().</p><p>if() is Sass’ conditional (ternary) operator. It takes three arguments: a condition and two return statements. If the condition is met, if() will return the first statement. Otherwise, it will return the second one. You can see it as an @if/@else shorthand.</p><pre>@mixin color-modifiers($attribute: &#39;color&#39;, $prefix: &#39;-&#39;, $separator: &#39;-&#39;, $base: &#39;base&#39;) {<br>  @each $name, $color in $colors {<br>    &amp;#{$prefix}#{$name} {<br>      @each $tone, $hex in $color {<br>        &amp;#{if($tone != $base, #{$separator}#{$tone}, &#39;&#39;)} {<br>          #{$attribute}: $hex;<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>Every time the nested @each loop will parse a $tone that’s different from “base,” it will return the $separator and the $tone as the class suffix. Else, it will return nothing, leaving the class as is.</p><pre>.text-grey {<br>  color: #404145;<br>}<br>.text-grey-light {<br>  color: #c7c7cd;<br>}<br>.text-yellow {<br>  color: #ecaf2d;<br>}<br>.text-green {<br>  color: #5ad864;<br>}</pre><h3>DRY-ing it all up</h3><p>In a real-world project, chances are you’ll want to use various map structures. For example, you could have one-level deep maps for font sizes and two-levels deep maps for colors. <strong>You’re not going to write a different mixin for each depth level</strong>. That would be repetitive and unmaintainable. You need to be able to rely on a single mixin to handle that.</p><p>We want a generic mixin to generate all modifiers, and one that’s able to handle multidimensional maps. If you compare the two mixins we came up with in this tutorial, you’ll notice they look a lot alike. The only difference is that one performs an extra loop before printing the computed CSS declaration. This is a typical job for a <strong>recursive mixin</strong>.</p><p>It will begin with an @each directive where we can start building our selector. This is where we’ll check if the current $key equals to “base” so we can decide to output it or not. Then, we’ll check if the current $value is a map itself: if yes, we need to run the mixin again from where we are and pass it the nested map. Otherwise, we can print the CSS declaration.</p><pre>@mixin modifiers($map, $attribute, $prefix: &#39;-&#39;, $separator: &#39;-&#39;, $base: &#39;base&#39;) {<br>  @each $key, $value in $map {<br>    &amp;#{if($key != $base, #{$prefix}#{$key}, &#39;&#39;)} {<br>      @if type-of($value) == &#39;map&#39; {<br>        @include modifiers($value, $attribute, $separator);<br>      }<br>      @else {<br>        #{$attribute}: $value;<br>      }<br>    }<br>  }<br>}</pre><p>And <em>voilà</em>! This mixin will work with maps of any depth. Feel free to use it in your own projects! If you like it, you can show some love by <a href="https://gist.github.com/sarahdayan/4d2cc04a636e8039f10a889a0e29fbd9">starring it on GitHub</a>. Also, if you want to improve it, please leave a comment on the gist so I can update it 👍</p><p><em>Originally published at </em><a href="https://frontstuff.io/generate-all-your-utility-classes-with-sass-maps"><em>frontstuff.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8921ab3b4508" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/how-to-generate-all-your-utility-classes-with-sass-maps-8921ab3b4508">How to generate all your utility classes with Sass Maps</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s make multi-colored icons with SVG symbols and CSS variables]]></title>
            <link>https://medium.com/free-code-camp/lets-make-your-svg-symbol-icons-multi-colored-with-css-variables-cddd1769fca4?source=rss-20bd5f22250b------2</link>
            <guid isPermaLink="false">https://medium.com/p/cddd1769fca4</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sarah Dayan]]></dc:creator>
            <pubDate>Wed, 31 Jan 2018 13:25:33 GMT</pubDate>
            <atom:updated>2018-01-31T14:11:35.470Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WO5mgu0bcFNdt7R6JH6mhQ.png" /><figcaption><a href="http://creativethings.io/">Creative Things</a> by <a href="http://kyleadams.me/">Kyle Adams</a></figcaption></figure><p>Long gone are the days of using images and CSS sprites to make icons for the web. With the explosion of web fonts, icon fonts have become the number one solution for displaying icons in your web projects.</p><p>Fonts are vectors, so you don’t have to worry about resolution. They benefit from the same CSS properties as text. As a result, you have full control over size, color, and style. You can add transforms, effects, and decorations such as rotations, underlines, or shadows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3CipXJBmc9h8Q-68.png" /><figcaption><em>No wonder projects like Font Awesome have been downloaded </em><a href="http://npm-stats.com/~packages/font-awesome"><em>more than 15 million times on npm alone</em></a><em> to this day.</em></figcaption></figure><p><strong>Icon fonts aren’t perfect though</strong>, which is why a growing number of people prefer using inline SVG images. CSS Tricks wrote a <a href="https://css-tricks.com/icon-fonts-vs-svg">list of areas where icon fonts fall short compared to native SVG elements</a>: sharpness, positioning, or even failures because of cross-domain loading, browser-specific bugs, and ad-blockers. Now you can circumvent most of these issues, generally making icon fonts a safe choice.</p><p>Yet, there’s one thing that remains absolutely impossible with icon fonts: <strong>multicolor support</strong>. Only SVG can do this.</p><p><strong><em>TL;DR</em></strong><em>: this post goes in-depth into the how and why. If you want to understand the whole thought process, read on. Otherwise you can look at the final code on </em><a href="https://codepen.io/sarahdayan/pen/GOzaEQ"><em>CodePen</em></a><em>.</em></p><h3>Setting up SVG symbol icons</h3><p>The problem with inline SVGs is how verbose they are. You don’t want to copy/paste all those coordinates every single time you need to use the same icon. This would be repetitive, hard to read, and a pain to maintain.</p><p>With SVG symbol icons, you have one copy of each SVG element, and you instantiate them anywhere with a reference.</p><p>You start by including the SVG inline, hide it, wrap it in a &lt;symbol&gt; and identify it with an id attribute.</p><pre>&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; style=&quot;display: none&quot;&gt;<br>  &lt;symbol id=&quot;my-first-icon&quot; viewBox=&quot;0 0 20 20&quot;&gt;<br>    &lt;title&gt;my-first-icon&lt;/title&gt;<br>    &lt;path d=&quot;...&quot; /&gt;<br>  &lt;/symbol&gt;<br>&lt;/svg&gt;</pre><p><em>The full SVG markup is included once and hidden in the HTML.</em></p><p>Then, all you have to do is instantiate the icon with a &lt;use&gt; element.</p><pre>&lt;svg&gt;<br>  &lt;use xlink:href=&quot;#my-first-icon&quot; /&gt;<br>&lt;/svg&gt;</pre><p><em>This will display an exact copy of your original SVG icon.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/0*QRBjEA0KVeKcjGBy.png" /></figure><p><strong>That’s it!</strong> Pretty nice, right?</p><p>You probably noticed the funny xlink:href attribute: this is the link between your instance and the original SVG.</p><p>It’s important to mention that xlink:href is a deprecated SVG attribute. Even if most browsers still support it, <strong>you should use </strong><strong>href instead</strong>. Now the thing is, some browsers like Safari don’t support SVG resource references through the href attribute, so you still need to provide xlink:href.</p><p>To be safe, provide both attributes.</p><h3>Adding some color</h3><p>Unlike with fonts, color doesn’t have any effect on SVG icons: you must use the fill attributes to define a color. This means that they won’t inherit parent text color like icon fonts do, but you can still style them in CSS.</p><pre>// HTML<br>&lt;svg class=&quot;icon&quot;&gt;<br>  &lt;use xlink:href=&quot;#my-first-icon&quot; /&gt;<br>&lt;/svg&gt;</pre><pre>// CSS<br>.icon {<br>  width: 100px;<br>  height: 100px;<br>  fill: red;<br>}</pre><p>From here, you can create other instances of the same icon with a different fill color.</p><pre>// HTML<br>&lt;svg class=&quot;icon icon-red&quot;&gt;<br>  &lt;use xlink:href=&quot;#my-first-icon&quot; /&gt;<br>&lt;/svg&gt;</pre><pre>&lt;svg class=&quot;icon icon-blue&quot;&gt;<br>  &lt;use xlink:href=&quot;#my-first-icon&quot; /&gt;<br>&lt;/svg&gt;</pre><pre>// CSS<br>.icon {<br>  width: 100px;<br>  height: 100px;<br>}<br>.icon-red {<br>  fill: red;<br>}<br>.icon-blue {<br>  fill: blue;<br>}</pre><p>It works, but this isn’t <strong>exactly</strong> what we want. So far, all we have done can be achieved with a regular icon font. What we want is to have a <strong>different</strong> color for each <strong>part</strong> of the icon. We want to fill each <strong>path</strong> with a different color, without altering other instances, and we want to be able to override it if necessary.</p><p>At first, you might be tempted to rely on specificity.</p><pre>// HTML<br>&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; style=&quot;display: none&quot;&gt;<br>  &lt;symbol id=&quot;my-first-icon&quot; viewBox=&quot;0 0 20 20&quot;&gt;<br>    &lt;title&gt;my-first-icon&lt;/title&gt;<br>    &lt;path class=&quot;path1&quot; d=&quot;...&quot; /&gt;<br>    &lt;path class=&quot;path2&quot; d=&quot;...&quot; /&gt;<br>    &lt;path class=&quot;path3&quot; d=&quot;...&quot; /&gt;<br>  &lt;/symbol&gt;<br>&lt;/svg&gt;</pre><pre>&lt;svg class=&quot;icon icon-colors&quot;&gt;<br>  &lt;use xlink:href=&quot;#my-first-icon&quot; /&gt;<br>&lt;/svg&gt;</pre><pre>// CSS<br>.icon-colors .path1 {<br>  fill: red;<br>}<br>.icon-colors .path2 {<br>  fill: green;<br>}<br>.icon-colors .path3 {<br>  fill: blue;<br>}</pre><p><strong>This won’t work.</strong></p><p>We’re trying to style .path1, .path2 and .path3 as if they were nested in .icon-colors, but technically speaking <strong>they’re not</strong>. The &lt;use&gt; element isn’t a <strong>placeholder</strong> that gets replaced by your SVG definition. It’s a <strong>reference</strong> which clones the content it’s pointing to into the <a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM"><strong>shadow DOM</strong></a> 😱</p><p><strong>What can we do then?</strong> How can we affect children content in a scoped way when said children aren’t in the DOM?</p><h3>CSS variables to the rescue</h3><p>In CSS, <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/inheritance">some properties</a> are inherited from ancestors to children. If you assign a text color to the body, all the text in the page will inherit that color until it’s overridden. The ancestor isn’t aware of the children, but the <strong>inheritable</strong> styles are still propagated.</p><p>In our early example, we inherited the fill property. Look again, and you’ll see that the class in which we declared a fill color is appended on the <strong>instances</strong>, not the definitions. This is how we were able to get different colors for each instance of a single definition.</p><p>Now here’s the problem: we want to pass <strong>different</strong> colors to <strong>different</strong> paths of the original SVG, but there’s only one fill attribute we can inherit from.</p><p>Meet <strong>CSS variables</strong>.</p><p>CSS variables are declared within rulesets just like any other property. You can name them anything you want, and assign them any valid CSS value. Then, you declare it as a <strong>value</strong> for itself, or any child property, and <strong>it will be inherited</strong>.</p><pre>.parent {<br>  --custom-property: red;<br>  color: var(--custom-property);<br>}</pre><p><em>All children of </em><em>.parent will have red text.</em></p><pre>.parent {<br>  --custom-property: red;<br>}<br>.child {<br>  color: var(--custom-property);<br>}</pre><p><em>All </em><em>.child nested in </em><em>.parent elements will have red text.</em></p><p>Now let’s apply this concept to our SVG symbol. We’ll use the fill attribute on each path of the SVG definition, and set them to different CSS variables. Then, we’ll assign them different colors.</p><pre>// HTML<br>&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; style=&quot;display: none&quot;&gt;<br>  &lt;symbol id=&quot;my-first-icon&quot; viewBox=&quot;0 0 20 20&quot;&gt;<br>    &lt;title&gt;my-first-icon&lt;/title&gt;<br>    &lt;path fill=&quot;var(--color-1)&quot; d=&quot;...&quot; /&gt;<br>    &lt;path fill=&quot;var(--color-2)&quot; d=&quot;...&quot; /&gt;<br>    &lt;path fill=&quot;var(--color-3)&quot; d=&quot;...&quot; /&gt;<br>  &lt;/symbol&gt;<br>&lt;/svg&gt;</pre><pre>&lt;svg class=&quot;icon icon-colors&quot;&gt;<br>  &lt;use xlink:href=&quot;#my-first-icon&quot; /&gt;<br>&lt;/svg&gt;</pre><pre>// CSS<br>.icon-colors {<br>  --color-1: #c13127;<br>  --color-2: #ef5b49;<br>  --color-3: #cacaea;<br>}</pre><p>And… <strong>it works</strong>! 🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/0*b9uBTmdvSJs7fd1D.png" /></figure><p>From now on, all we need to do to create an instance with a different color scheme is to create a new class.</p><pre>// HTML<br>&lt;svg class=&quot;icon icon-colors-alt&quot;&gt;<br>  &lt;use xlink:href=&quot;#my-first-icon&quot; /&gt;<br>&lt;/svg&gt;</pre><pre>// CSS<br>.icon-colors-alt {<br>  --color-1: brown;<br>  --color-2: yellow;<br>  --color-3: pink;<br>}</pre><p>If you still want to have monochrome icons, <strong>you don’t have to repeat the same color on every CSS variable</strong>. Instead, you can declare a single fill rule: because CSS variables aren’t defined, it will fall back on your fill declaration.</p><pre>.icon-monochrome {<br>  fill: grey;<br>}</pre><p><em>Your </em><em>fill declaration will work because the </em><em>fill attributes on the original SVG are set with undefined CSS variables values.</em></p><h3>What to name my CSS variables?</h3><p>There are usually two routes you can take when it comes to naming things in CSS: <strong>descriptive</strong> or <strong>semantic</strong>. Descriptive means calling a color <strong>what it is</strong>: if you’re storing #ff0000, you’d call it --red. Semantic means calling the color by <strong>how it’s applied</strong>: if you’re using #ff0000 for the handle of a coffee cup, you’d call it --cup-handle-color.</p><p>Descriptive names might be your first instinct. It feels DRYer since #ff0000 can be used for other things than the handle of the coffee cup. A --red CSS variable is reusable for other icon paths that need to be red. After all, this is how utility-first CSS works and <a href="https://frontstuff.io/in-defense-of-utility-first-css">it’s a fine system</a>.</p><p>Problem is, in our case <strong>we can’t apply granular classes to the elements we want to style</strong>. Utility-first principles can’t apply, because we have a single reference for each icon, and we have to style it through class variations.</p><p>Using semantic class names, like --cup-handle-color for example, makes more sense for this use case. When you want to change the color of a part of an icon, you instantly know what it is and what to override. The class name will remain relevant no matter what color you assign.</p><h3>To default or not to default</h3><p>It’s tempting to make the multi-colored version of your icons their default state. This way, you could use them with no need for extra styling, and you would add your own classes only when necessary.</p><p>There are two ways to achieve that: <strong>:root</strong> and <strong>var() default</strong>.</p><h3>:root</h3><p>You can define all your CSS variables on the :root selector. This keeps them all in one place and allows you to “share” similar colors. :root has the lowest priority, so it remains easy to override.</p><pre>:root {<br>  --color-1: red;<br>  --color-2: green;<br>  --color-3: blue;<br>  --color-4: var(--color-1);<br>}</pre><pre>.icon-colors-alt {<br>  --color-1: brown;<br>  --color-2: yellow;<br>  --color-3: pink;<br>  --color-4: orange;<br>}</pre><p>However, <strong>there are major drawbacks to this method</strong>. First, keeping color definitions separate from their respective icons can be confusing. When you decide to override them, you have to go back and forth between the class and the :root selector. But more importantly, <strong>it doesn’t allow you to scope your CSS variables</strong>, thus keeps you from reusing the same names.</p><p>Most of the time, when an icon only uses one color, I use the --fill-color name. It’s simple, understandable, and it makes sense to use the same name for all icons that only need one fill color. If I have to declare all variables in the :root declaration, I can’t have several --fill-color. I’ll be forced to define --fill-color-1, --fill-color-2, or use namespaces like --star-fill-color, --cup-fill-color.</p><h3>var() default</h3><p>The var() function, which you use to assign a CSS variable to a property, can take a default value as a second argument.</p><pre>&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; style=&quot;display: none&quot;&gt;<br>  &lt;symbol id=&quot;my-first-icon&quot; viewBox=&quot;0 0 20 20&quot;&gt;<br>    &lt;title&gt;my-first-icon&lt;/title&gt;<br>    &lt;path fill=&quot;var(--color-1, red)&quot; d=&quot;...&quot; /&gt;<br>    &lt;path fill=&quot;var(--color-2, blue)&quot; d=&quot;...&quot; /&gt;<br>    &lt;path fill=&quot;var(--color-3, green)&quot; d=&quot;...&quot; /&gt;<br>  &lt;/symbol&gt;<br>&lt;/svg&gt;</pre><p>Until you define --color-1, --color-2 and --color-3, the icon will use the default values you set for each &lt;path&gt;. This solves the global scope issue we have when using :root, but be careful: <strong>you now have a default value and it’s doing its job</strong>. As a result, you can’t use a single fill declaration to define monochrome icons anymore. You’ll have to assign the color to every CSS variable used on the icon, one by one.</p><p>Setting default values can be useful, but it’s a tradeoff. I suggest you don’t make it a habit, and only do it when it makes sense for a given project.</p><h3>How browser-friendly is all that?</h3><p><a href="https://caniuse.com/#feat=css-variables">CSS variables are compatible with most modern browsers</a>, but as you probably expect it, Internet Explorer doesn’t support it <strong>at all</strong>. Not even IE11, and since development was discontinued in favor of Edge, there’s no chance it will ever get up to speed.</p><p>Now, just because a feature isn’t supported by a browser you need to cater to, that doesn’t mean you have to rule it out altogether. In such cases, go for <strong>graceful degradation</strong>: offer multi-colored icons to modern browsers, and provide a fallback fill color for older ones.</p><p>What you want to do is set a declaration that will only work if CSS variables aren’t supported. This can be achieved by setting the fill property to the fallback color: if CSS variables are supported, it won’t even be taken into account. If they’re not, your fill declaration will apply.</p><p>If you’re using Sass, this can be abstracted into a @mixin.</p><pre>@mixin icon-colors($fallback: black) {<br>  fill: $fallback;<br>  @content;<br>}</pre><p>We can now define color schemes without worrying about browser compatibility.</p><pre>.cup {<br>  @include icon-colors() {<br>    --cup-color: red;<br>    --smoke-color: grey;<br>  };<br>}</pre><pre>.cup-alt {<br>  @include icon-colors(green) {<br>    --cup-color: green;<br>    --smoke-color: grey;<br>  };<br>}</pre><p><em>Passing the CSS variables in the mixin through </em><em>@content is optional. If you do it outside, the compiled CSS will be the same. But it can be helpful to package it all in one place: you can fold snippets in your editor and visually identify declarations that go together.</em></p><p>Check out <a href="https://codepen.io/sarahdayan/pen/GOzaEQ/">this pen</a> on different browsers. On up-to-date versions of Firefox, Chrome, and Safari, the last two cups will respectively be red with grey smoke and blue with grey smoke. On Internet Explorer and Edge before version 15, the third cup will be all red and the fourth will be all blue! ✨</p><p>If you want to learn more about SVG symbol icons (and SVG in general), I <strong>strongly</strong> suggest you read <a href="https://www.sarasoueidan.com/blog">everything by Sara Soueidan</a>. And if you have any question about CSS symbol icons, don’t hesitate to hit me up on <a href="https://twitter.com/frontstuff_io">Twitter</a>!</p><p><em>Originally published at </em><a href="https://frontstuff.io/multi-colored-svg-symbol-icons-with-css-variables"><em>frontstuff.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cddd1769fca4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/lets-make-your-svg-symbol-icons-multi-colored-with-css-variables-cddd1769fca4">Let’s make multi-colored icons with SVG symbols and CSS variables</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[In Defense of Utility-First CSS]]></title>
            <link>https://medium.com/free-code-camp/in-defense-of-utility-first-css-4f406acee6fb?source=rss-20bd5f22250b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f406acee6fb</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[sass]]></category>
            <category><![CDATA[atomic-css]]></category>
            <category><![CDATA[bem]]></category>
            <category><![CDATA[utility-first]]></category>
            <dc:creator><![CDATA[Sarah Dayan]]></dc:creator>
            <pubDate>Sat, 27 Jan 2018 01:13:30 GMT</pubDate>
            <atom:updated>2018-01-27T13:09:58.149Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nHfoojHD3eS-ggpdB6zNJw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/TL5Vy1IM-uA?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Iker Urteaga</a> on <a href="https://unsplash.com/search/photos/lego%20bricks?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><strong><em>“Favor composition over inheritance”</em></strong>.</p><p>This piece of wisdom from <a href="https://en.wikipedia.org/wiki/Design_Patterns"><em>Design Patterns</em></a>, one of the most influential software engineering books, is the foundation of <strong>utility-first CSS</strong>. It also shares many principles with <strong>functional programming</strong>: immutability, composability, predictability, and avoidance of side-effects. The goal behind all those fancy terms is to write code that’s <strong>easier to maintain and to scale</strong>.</p><p>Despite its growing popularity, utility-first CSS still hasn’t convinced everyone. While some <a href="http://jon.gold/2015/07/functional-css">praise it</a>, others have been <a href="http://www.zeldman.com/2017/01/03/kiss-my-classname">vividly critical</a> about such a practice. <strong>I used to be in the latter group</strong>. I was a BEM fan, sold to an approach I adopted for its advantages and ended up rooting for it like we do for a sports team. I rejected utility-first because it implied that my beloved and familiar approach wasn’t good anymore.</p><p>Since then, I’ve dived <em>a lot</em> deeper into the topic. I studied design patterns and functional programming. This allowed me to <strong>radically revise my judgment</strong>.</p><p><a href="https://css-tricks.com/growing-popularity-atomic-css/">CSS Tricks</a> and <a href="https://adamwathan.me/css-utility-classes-and-separation-of-concerns">Adam Wathan</a> have done a brilliant job at taking us on a journey from “regular” CSS to utility-first, and explaining the “why” behind it. Rather than paraphrasing, I’ll focus on <strong>the recurring criticism of utility-first </strong>and debunk common misconceptions.</p><h3>“Might as well use inline styles”</h3><p>People often compare utility-first CSS to applying CSS rules to HTML nodes through the style attribute. This way of styling is unanimously considered a bad practice, and we have since moved on to separate stylesheets and class abstractions.</p><p><strong>Utility-first CSS is no different</strong>. All styles are defined and maintained separately. This allows code reuse, usage of pseudo-classes, pseudo-elements, pre-processors, and browser caching.</p><p>Yet, atomic CSS detractors hurriedly associate it to inline styles. Atomic classes are small, they often have only one rule, and they’re named in a <em>functional</em> way instead of being <em>semantic</em>.</p><p>All that being said, just because it <em>looks</em> the same doesn’t mean it <em>is</em> the same. Understanding how both practices differ is key to grasping the benefits of utility-first.</p><p><strong>Inline styles allow you to do anything you want</strong>. You don’t have to follow any pre-existing definition. You’re re-writing everything from the ground-up every time you style a new HTML node. Similar elements end up with duplicate code, which makes the page unnecessarily heavier. If you’re not careful, it’s easy to ignore pre-existing solutions and reinvent the wheel every time.</p><pre>&lt;h2 style=&quot;font-size: 16px; font-weight: bold; color: purple&quot;&gt;Stranger Things&lt;/h2&gt;<br>&lt;p style=&quot;font-size: 13px; font-style: italic&quot;&gt;Stranger Things is an American science fiction-horror web television...&lt;/p&gt;<br>&lt;h2 style=&quot;font-size: 16px; font-weight: bold; color: purple&quot;&gt;Game of Thrones&lt;/h2&gt;<br>&lt;p style=&quot;font-size: 13px; font-style: italic&quot;&gt;Game of Thrones is an American fantasy drama television...&lt;/p&gt;</pre><p><em>Unnecessarily verbose, heavier file size, multiple sources of truth for a single design concept.</em></p><pre>&lt;button style=&quot;padding: 5px 8px; font-size: 13px&quot;&gt;Button&lt;/button&gt;<br>&lt;button style=&quot;padding: 0 8px; font-size: 13px; line-height: 23px&quot;&gt;Button&lt;/button&gt;<br>&lt;button style=&quot;display: flex; padding: 0 8px; font-size: 13px; height: 23px; align-items: center&quot;&gt;Button&lt;/button&gt;</pre><p><em>Three attempts at solving the same problem. This is easily induced by the absence of a single source of truth, and likely to cause visual inconsistencies.</em></p><p><strong>Utility classes expose a well-defined API that you can use to compose more complex components</strong>. You’re not re-writing styles; instead, you’re relying on classes that define styles and behaviors once and for all.</p><pre>// HTML</pre><pre>&lt;h2 class=&quot;font-16 font-bold font-purple&quot;&gt;Stranger Things&lt;/h2&gt;<br>&lt;p class=&quot;font-13 font-italic&quot;&gt;Stranger Things is an American science fiction-horror web television...&lt;/p&gt;<br>&lt;h2 class=&quot;font-16 font-bold font-purple&quot;&gt;Game of Thrones&lt;/h2&gt;<br>&lt;p class=&quot;font-13 font-italic&quot;&gt;Game of Thrones is an American fantasy drama television...&lt;/p&gt;</pre><pre>// CSS</pre><pre>/* Font sizes */</pre><pre>.font-13 { font-size: 13px } <br>.font-16 { font-size: 16px }<br>...</pre><pre>/* Font styles */</pre><pre>.font-bold { font-weight: bold }<br>.font-italic { font-style: italic }<br>...</pre><pre>/* Font colors */</pre><pre>.font-purple { color: purple }<br>...</pre><p>Using a defined set of existing CSS rules, no matter how atomic, forces you to pick styles from a <strong>limited list</strong>. You’re not granted total freedom like you are with inline styles. You’re maintaining a consistent catalog of <em>allowed</em> styles, and using them to <em>compose</em> larger components.</p><p>This approach enforces consistency by limiting the ways you can style elements. Instead of having access to 16+ million colors, you only have access the number of colors defined in your theme.</p><p><strong>It also provides a single source of truth. </strong>Instead of re-declaring the same color for each element that uses it, you define it once in a class and use that class wherever you need it. In addition, using separate styling (with atomic classes or not) gives you access to pseudo-classes and pseudo-elements, pre-processors, caching… a whole load of benefits that aren’t available with inline styles.</p><p>You may argue that it doesn’t matter if atomic styles are limited: carelessly mixing them may result in inconsistent layouts like with inline styles. But that’s <strong>a human issue, not a technical one</strong>. You get the exact same problem with any approach, and any language for that matter, whether you’re able to scope or not. If you don’t follow the rules, style guides, and best practices that your team put in place, you’re the one to blame. Not the program, not the language, and not the architecture.</p><h3>“It violates separation of concerns”</h3><p>One of the biggest arguments against functional CSS is that it goes against separation of concerns. That CSS should strictly be in charge of the styling, and HTML should semantically structure the page. That by using atomic classes and composing components in the HTML, you’re somewhat delegating styling to the HTML instead of doing it in CSS.</p><p><strong>This is an extreme, and ultimately warped, vision of what “separation of concerns” means.</strong></p><p>A few years ago, I was on a job interview with a front-end developer who told me about his sheer disdain for Bootstrap. According to him, using extra markup to create a grid was a heresy: that’s a job for CSS, and CSS only. HTML should be 100% oblivious to how it’s rendered.</p><p>The problem with that kind of thinking is that it’s <strong>deeply impractical</strong>. It raises design principles to a dogmatic level, ignoring concrete use-cases and context. It pushes you to be more concerned about checking all the “good practice” checkboxes than solving actual problems.</p><p>Adam Wathan <a href="https://adamwathan.me/css-utility-classes-and-separation-of-concerns">explains it well (see: “Separation of concerns” is a straw man)</a>: when it comes to HTML and CSS, you can’t look at it from a strict “separation of concerns” perspective. <strong>It’s a “which depends on which” relationship</strong>.</p><p><strong>Make no mistake:</strong> just because style composition is performed in the HTML <em>document</em> doesn’t mean it’s done <em>in HTML</em>. We’re not using <em>style</em> or <em>align </em>attributes on HTML nodes. We’re assembling pieces that we defined in a proper stylesheet, <em>in CSS</em>. Our HTML becomes a <em>consumer</em> of our CSS “API.” As Vue.js explains it in their <a href="https://vuejs.org/v2/guide/single-file-components.html#What-About-Separation-of-Concerns">documentation</a>, separation of concerns doesn’t equal separation of file types. Your styles can be composed on HTML nodes, <strong>it’s still a CSS job</strong>.</p><h3>“It bloats the HTML”</h3><p>When people mention code bloat, they usually mean one of two things (or both): code that’s <a href="https://frontstuff.io/in-defense-of-utility-first-css#its-ugly-and-hard-to-read"><strong>hard to read</strong></a>, and a <strong>heavier codebase</strong>.</p><p>The complexity of your layout has to exist <em>somewhere</em>. A component-first approach doesn’t remove “bloat,” it only <em>deports</em> it to the stylesheet. Even so, because your larger components reuse the same atomic styles as others, <strong>you inevitably end up with duplicate code</strong>.</p><pre>$green: #74b759;</pre><pre>.component {<br>  &amp;-title {<br>    color: $green;<br>    font-weight: bold;<br>  }<br>}</pre><pre>.widget {<br>  &amp;-title {<br>    color: $green;<br>    font-style: italic;<br>  }<br>}</pre><pre>.footer {<br>  &amp;-links {<br>   color: $green;<br>   text-decoration: underline;<br>  }<br>}</pre><p><em>Even with Sass, you get duplicate rules in the source code. </em><em>@mixin can help, but you still get duplicates in the compiled CSS.</em></p><p>Now I know what you’re thinking. We got @extend. That’s an ideal use case for it, right?</p><p>Not so fast.</p><p>@extend may avoid ruleset duplication in the compiled CSS, but the mega comma-separated selector it will generate could end up being <strong>a lot heavier than if you had duplicated the rule</strong>. So much for avoiding bloat.</p><p>You’re also concatenating unrelated classes <strong>and moving them all to the top</strong>, where the first @extend takes place. This can quickly result in specificity issues and odd overrides. Not to mention that you can’t @extend an outer class or placeholder from within a media query. So yeah, definitely not a silver bullet.</p><p>From a file size standpoint, <strong>you shouldn’t worry about repeated class names in the HTML</strong>. That’s what Gzip is for. The <em>deflate</em> algorithm was <a href="http://www.gzip.org/algorithm.txt">specifically made</a> to handle duplicate strings, so there’s no point in trimming away characters in your HTML. The resulting file size will make <strong>little to no difference</strong> whether you use a few or a lot of classes.</p><p>On the other hand, the more a <em>selector</em> is repeated in a stylesheet, <strong>the more work your browser has to do to resolve all styles</strong>. If you have a single .title-green class for a given style, it simply matches all .title-green in the page. But if you have many classes doing the same thing (using @mixin) or similar selectors doing different things (using @extend), the more expensive it will be for the browser to match.</p><p>HTML “bloat” doesn’t matter, <strong>but CSS does</strong>. The network and engine don’t care how many classes you have in your HTML, but the way you write your CSS counts. If your decision-making process revolves around performances, make sure you focus your attention on the right things.</p><h3>“BEM is enough”</h3><p>OOCSS and all derived methods (SMACSS, BEM, etc.) drastically improved how we handle CSS. Utility-first CSS is an heir of this approach: it, too, defines reusable <em>objects</em>.</p><p>The problem with BEM is that it focuses on building components first. Instead of looking for the smallest, unsplittable patterns, you’re building <em>blocks</em> and their child <em>elements</em>. BEM does an excellent job at namespacing and preventing style leaks, but its component-first nature inevitably leads to <a href="http://wiki.c2.com/?PrematureAbstraction">premature abstraction</a>. You make a component for a certain use-case and end up never reusing it (a navbar component, for example).</p><p>BEM encourages you to use <em>modifiers</em> to handle component variations. This may seem smart at first, but unfortunately leads up to other problems. You end up creating tons of modifiers you only use once for a specific use-case. Worse: from one component to another, you might end up with similar modifiers, further breaking the <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a> principle.</p><pre>.card {<br>  background: white;<br>  border: 1px solid grey;<br>  text-align: justify;<br>}</pre><pre>.card--left {<br>  text-align: left;<br>}</pre><pre>.card--right {<br>  text-align: right;<br>}</pre><pre>.tooltip {<br>  background: black;<br>  color: white;<br>  text-align: center;<br>}</pre><pre>/* Oops, looks like duplicate rules down there! */</pre><pre>.tooltip--left {<br>  text-align: left;<br>}</pre><pre>.tooltip--right {<br>  text-align: right;<br>}</pre><p>At scale, components can become hard to change without breaking instances throughout a project. Premature abstraction keeps components from evolving and splitting into independent entities if they need to. Modifiers multiply as an attempt to fix it, resulting in non-reusable variations for unicorn use-cases, and undo band-aids when we realize our component does too much.</p><p>BEM is a great attempt at fixing inherent CSS problems, but making it the core CSS approach of your project brings all the problems you meet when favoring inheritance over composition.</p><h3>“It’s a whole other language to learn on top of CSS”</h3><p>This statement can be said of any naming system for any specific project, whatever methodology you pick. Your CSS class names ecosystem is a layer of abstraction on top of pure CSS. Whether you’re using semantic names like .card or functional ones like .bg, new contributors will need to familiarize themselves with what does what and when to use it.</p><p>You can’t escape having to use a naming interface between your HTML and CSS, unless you’re willing to describe your exact markup in CSS or write inline styles. Ultimately, functional class names are <a href="https://frontstuff.io/in-defense-of-utility-first-css#its-ugly-and-hard-to-read">easier to understand</a> because they describe the style. You know what they do without having to lookup the actual styles, while semantic names force you to either look at the rendering or browse code.</p><h3>“It’s unmaintainable”</h3><p>When people say utility-first CSS is unmaintainable, they often mention that when something changes in the design, you have to change it everywhere. You have buttons with regular corners and you decide to make them rounded, so you need to add the .rounded-corners utility class on every button in the code. Yet, the whole point of utility-<em>first</em> is that you start composing with utility classes, and then create components when you start identifying repetitive patterns.</p><p>A button is an ideal and most obvious candidate for being abstracted into its own component. You might not even need to go through the “utility-first, then component” phase for this case. When it comes to larger components, favoring composition <em>first</em> is the best choice for maintainability. Why? <strong>Because it’s safer to add or remove classes on a specific HTML node</strong> than to add or remove styles in a class that applies on many elements.</p><p>Too many times have I been subjected to changing designs, and had to duplicate existing components to make them behave differently because I had no other choice. Even when a designer supplies all designs at the beginning of a project, and even if you do a great job at identifying components before you code, <strong>you can’t predict the future</strong>.</p><p>Let’s say initial designs have white cards with an inset box shadow and a little ribbon in the corner.</p><pre>// CSS</pre><pre>.card {<br>  position: relative;<br>  background: white;<br>  padding: 22px;<br>  border: 1px solid lightgrey;<br>  text-align: justify;<br>  border-radius: 5px;<br>  box-shadow: 0 0 5px 0 rgba(0, 0, 0, .2);<br>  overflow: hidden;<br>}</pre><pre>.card::after {<br>  position: absolute;<br>  top: -11px;<br>  right: 9px;<br>  display: block;<br>  width: 10px;<br>  height: 50px;<br>  background: red;<br>  transform: rotateZ(-45deg);<br>  content: &#39;&#39;;<br>}</pre><pre>// HTML</pre><pre>&lt;div class=&quot;card&quot;&gt;...&lt;/div&gt;</pre><p>This solution is simple, semantic, and reusable. You handle everything in CSS and have minimal HTML to write. But suddenly you get new designs for new pages, and they use the card without the ribbon. Now you have to find a way to remove the ribbon for these new cards.</p><pre>.card-no-ribbon::after {<br>  display: none;<br>}</pre><p>Problem is, this class is <em>undoing</em> something that was previously designed. Having to <em>add</em> a class to <em>remove</em> a feature is an anti-pattern: <strong>it’s counter-intuitive and hard to maintain</strong>. When you decide to change how the base class behaves, you need to keep an eye on the undo modifier to make sure it still works.</p><p>We now need to add another ribbon to the bottom left.</p><pre>.card::before,<br>.card::after {<br>  /* shared code */<br>}</pre><pre>.card::before {<br>  top: -11px;<br>  right: 9px;<br>}</pre><pre>.card::after {<br>  bottom: -11px;<br>  left: 9px;<br>}</pre><p>But now we need to update .card-no-ribbon!</p><pre>.card-no-ribbon::before,<br>.card-no-ribbon::after {<br>  display: none;<br>}</pre><p>This, right here, <strong>is the fragile base class anti-pattern in action</strong>. Because your base class was abstracted too soon, is doing too much, and now needs to evolve, you can’t edit it without worrying about possible side-effects. If new people start contributing to the project, those risks multiply by ten.</p><p>The only option you have left this stage is to do a refactor: have a nude .card as the base class, and add the ribbons with .card--top-ribbon and .card--bottom-ribbon modifiers. But now you have to edit all the existing .cards in your code that <em>do</em> need to have a ribbon.</p><p><strong>Early refactors are a pretty good indicator of unmaintainability</strong>.</p><p>You could argue that a smart developer <em>could</em> have seen it coming. That they <em>should</em> have made a naked .card base class and a .card--ribbon modifier, right from the start.</p><p><strong>That’s actually making a case <em>in favor</em> of utility-first and composition</strong>.</p><p>You’re taking the decision to break down a given design element that you deemed too monolithic, so it’s easier to scale. <strong>That’s a good call.</strong> The more you go, the more you’ll realize this leads to utility-first.</p><p>You might think it doesn’t, and that your job is to <em>foresee</em> what is the bare minimum for a given component. But unless you own a crystal bowl, this is a risky assessment. This is also short-sighted. What if parts of your component need to be extended to other components? For example, what if you now need buttons with ribbons? If you duplicate the .card--ribbon class, your code isn’t DRY anymore, which makes it even more unmaintainable. So? Make a mixin and import it into both modifiers? Again, that’s extra work and “wet” code.</p><p>The best solution for this use-case is to write a single utility class for the ribbon, and modifiers for sizes and colors if necessary. This allows you to have <strong>a single source of truth</strong> and use the ribbon anywhere you want to. If you need to put ribbons on avatars, panels, unordered lists, modals, you can do it without having to write a single extra line of CSS.</p><p><strong>This is the definition of scalability and maintainability</strong>. All you have to do is reuse the available code you wrote <em>proactively</em>, instead of having to tweak existing code <em>reactively</em>.</p><pre>.ribbon {<br>  position: relative;<br>  overflow: hidden;<br>}</pre><pre>.ribbon::after {<br>  position: absolute;<br>  display: block;<br>  top: -11px;<br>  right: 9px;<br>  width: 10px;<br>  height: 50px;<br>  background: red;<br>  transform: rotateZ(-45deg);<br>  content: &#39;&#39;;<br>}</pre><p><em>By breaking down designs into small elements, we write much more reusable code.</em></p><p>Calling utility-first CSS “unmaintainable” is absolutely inaccurate. In fact, <strong>it may be the most maintainable and scalable CSS methodology to this day.</strong></p><p>You can’t predict the future.<strong> </strong>This is why you should always favor composition over inheritance. <strong>A good sign of a healthy and scalable codebase is how things go when you need to change it.</strong></p><p>If a new change makes you anxious because you might break something, it’s a sign of poor design. But I would go a step further and say that if you need to write new CSS to make an existing component do something that another component already does, your code isn’t as scalable as you think it is.</p><p>If you need to reuse behavior that exists somewhere, <strong>you shouldn’t have to write new code</strong>. You should be able to trust and use what you already wrote and go from there. You have one source of truth on which you can rely, instead of two or more slight variations that you must not forget to keep up to date. <strong>This is the definition of maintainability.</strong></p><h3>“It’s ugly and hard to read”</h3><p>Do you remember the uproar when BEM started to become popular? I do. I remember many people who rejected the whole thing because of its syntax. Praising the model, but disgusted with the idea of chaining two underscores or two hyphens.</p><p>As humans, it’s in our nature to be easily put off by what we’re not familiar with. Yet, letting subjective cosmetic considerations come in the way of a potentially useful technique is where developers should draw the line. Our job is to <strong>solve problems</strong>. Our main concern should be <strong>the end user</strong>.</p><p>Look at the source code of many big projects: most of them have ended up adopting BEM. Chances are not all their front-end developers were sold at the beginning.</p><p>Overcoming initial feelings, especially if driven by personal preference, isn’t that hard <strong>when you’re putting the success of a project first</strong>.</p><p>Now on the topic of legibility, I get that long strings of classes can be “scary” when you open a file for the first time. This is not an insurmountable task though. More verbose code is a trade-off of composition, but it’s a <strong>much lesser inconvenience than unscalability</strong>.</p><p>I don’t use shorthands like .pt-8 or .bb-lemon in my own code. I favor full-length class names like .padding-top-8 and .border-bottom-lemon, which are much easier to read. Autocomplete solves the problem of having to type long class names, and there are tools you can use to re-hash class names into smaller ones for production. I doubt this will make any significant change to your performances but hey, if it makes you feel good to shave bytes away, knock yourself out 😊</p><p>Ultimately, the nature of functional class names might actually be <strong>more expressive</strong>. It’s easy for your brain to make a connection between such a class and what’s happening on screen. Even if you don’t get to see how it renders, you can get a pretty good idea of what .hidden or .opacity-6 are supposed to do.</p><pre>&lt;blockquote class=&quot;border-thick-left-red padding-left-medium font-navy&quot;&gt;<br>  &lt;p&gt;You know how they call a Quarter Pounder with Cheese in Paris?&lt;/p&gt;<br>&lt;/blockquote&gt;</pre><p><em>Stylistically speaking, it’s pretty easy to know what’s going on here.</em></p><p>Semantic class names don’t convey the same thing. It works for small components like buttons or alerts, which are common enough to be easily recognized. Yet, the bigger and the more complex a component gets, the less obvious it is to know what class name maps to what element on the screen, or what it looks like.</p><pre>&lt;div class=&quot;entry&quot;&gt;<br>  &lt;h2 class=&quot;entry-title&quot;&gt;The Shining&lt;/h2&gt;<br>  &lt;div class=&quot;widget widget-lead&quot;&gt;<br>    &lt;div class=&quot;widget-content&quot;&gt;<br>      &lt;p&gt;His breath stopped in a gasp. An almost drowsy terror stole through his veins...&lt;/p&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;author&quot;&gt;<br>      &lt;img class=&quot;author-avatar&quot; src=&quot;...&quot;&gt;<br>      &lt;h3 class=&quot;author-name&quot;&gt;Stephen King&lt;/h3&gt;<br>      &lt;p&gt;Stephen Edwin King (born September 21, 1947) is an American author of horror, supernatural fiction, suspense, science fiction, and fantasy...&lt;/p&gt;<br>      &lt;div class=&quot;btn-group&quot;&gt;<br>        &lt;a class=&quot;btn&quot; href=&quot;#&quot;&gt;Website&lt;/a&gt;<br>        &lt;a class=&quot;btn&quot; href=&quot;#&quot;&gt;Twitter&lt;/a&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p><em>Harder to know what class does what without going through the stylesheet.</em></p><p>In that way, functional classes are a lot easier to understand than semantic class names. They demand less catching up time and less file-switching. Ultimately, they give you the very bit of information you’re looking for anyways.</p><h3>“It’s not how you write CSS”</h3><p><strong>CSS specificity is a <em>feature</em>, not a bug.</strong> Use it correctly, and it will give you amazing control.</p><p>That’s what CSS veterans say when yet another article about the dangers of specificity pops up. And technically <strong>they’re right</strong>: the CSS priority system isn’t an accident. It usually bothers people who don’t master CSS because of the lack of scope. But a language isn’t broken because it doesn’t behave like what you’re used to. Nested CSS rules are like !important: they’re handy, but have been so poorly used for years that we now see it as something to <em>avoid</em>.</p><p>Specificity should be used proactively, not reactively. They should be <em>design decisions</em>, not a quick fix when your styles don’t apply. Harry Roberts explains it well in <a href="https://cssguidelin.es/#specificity">CSS Guidelines</a>:</p><blockquote>“The problem with specificity isn’t necessarily that it’s high or low; it’s the fact it is so variant and that it cannot be opted out of: the only way to deal with it is to get progressively more specific”.</blockquote><p>Specificity is a powerful tool, but it needs to be used with uppermost caution and a good long-term vision of the project. Use them wrong, and you’ll feel the pain of having to go back. Keeping specificity low avoids problems altogether: it relies solely on source order, which is <a href="https://www.xfive.co/blog/itcss-scalable-maintainable-css-architecture">a lot easier to manage</a>. With atomic CSS, if a style doesn’t apply, fixing it is as simple as adding or removing a class on an HTML node. You don’t have to call your stylesheet’s structure into question, which is a lot easier and safer to manage.</p><pre>// CSS</pre><pre>.color-navy {<br>  color: navy;<br>}</pre><pre>.color-red {<br>  color: red;<br>}</pre><pre>// HTML</pre><pre>&lt;div class=&quot;color-red color-navy&quot;&gt;<br>  &lt;p&gt;- Whose motorcycle is this?&lt;/p&gt;<br>  &lt;p&gt;- It&#39;s a chopper baby.&lt;/p&gt;<br>  &lt;p&gt;- Whose chopper is this?&lt;/p&gt;<br>  &lt;p&gt;- It&#39;s Zed&#39;s.&lt;/p&gt;<br>  &lt;p&gt;- Who&#39;s Zed?&lt;/p&gt;<br>  &lt;p&gt;- Zed&#39;s dead baby, Zed&#39;s dead.&lt;/p&gt;<br>&lt;/div&gt;</pre><p><em>Want the text to be navy? No need to touch the CSS. Simply remove the </em><em>.color-red class from the encompassing </em><em>&lt;div&gt;. If you need one of the children to be red, then move the </em><em>.color-red on it.</em></p><blockquote>“If a feature is sometimes dangerous, and there is a better option, then always use the better option.” — Douglas Crockford</blockquote><p>Using specificity or not isn’t about showing how well you master CSS and how <em>you</em>, unlike others, can keep it under control. It’s about <strong>understanding the advantages and flaws of the features at your disposal</strong>, and making choices in the best interest of the project.</p><h3>“You end up with plenty of unused CSS”</h3><p>Let’s say you’re using Sass maps to <a href="http://frontstuff.io/generate-all-your-utility-classes-with-sass-maps">generate your utility classes</a>. Colors, font sizes, backgrounds, everything is automatically compiled into proper, ready-to-use CSS. Problem is, if you don’t <em>use</em> everything, you’re left with useless extra bytes in production. This can easily be fixed with <a href="https://github.com/giakki/uncss">UnCSS</a>.</p><p>UnCSS is great at dusting off your stylesheets, but it comes with <strong>two caveats</strong>: it only works on HTML files (so, no PHP and no template files) and it only takes into account the JavaScript that’s executed on page load (not classes added on user interactions, for example). If you’re using a language like PHP to render your pages, you can add a job in your deployment workflow that compiles pages into temporary HTML and runs UnCSS on them. For the second issue, you can use the ignore option to list out that are classes added on user interaction.</p><p>Now it’s also important to ponder this issue. The cost of unused classes is heavier stylesheets (longer to download) and longer parse time. If you have a lot, and by that I mean a large percentage of your total styles, of unused classes, <strong>this can hurt performances</strong>. If you only have a few here and there, <strong>the impact will be negligible</strong>.</p><p>Maintaining your CSS codebase is your job as a developer. No matter what methodology you choose, you have to keep an eye on the project and make sure to remove dead code when things change.</p><p><strong>Being careless with that is how you end up with plenty of unused classes, not because you’re generating some of them</strong>.</p><p>Need a text color class only for the main color? Make a class for this one only. Need backgrounds for most colors in the theme, yet unsure you’ll use them all right away? Generate the damn classes. They’ll be ready when you need them, you won’t have to maintain them when you add new colors, and the extra code will cost <em>nothing</em>. <strong>This is not where your app’s bottlenecks are</strong>. If you’re having performances issues, there are a million other things to consider before even looking into your CSS.</p><h3>“It makes it hard to know what’s available to use”</h3><p>When your CSS codebase is a large collection of small utility classes, reading the source code won’t help you get a good overview of the available styles. But <strong>is it the role of the source code anyway</strong>?</p><p>It certainly isn’t. That’s what <strong>style guides</strong> are for.</p><p>Exploring source code is <em>far</em> from being enough to get a good understanding of how a full API is designed. This isn’t limited to atomic CSS: OOCSS or BEM projects, even small ones, can reach a level of sophistication which requires at least a README.</p><p>Can you imagine having to crawl back in an unminifed version of the master Bootstrap stylesheet every time you don’t remember if this is .col-md-offset-6 or .col-offset-md-6? Would anyone new to Bootstrap understand what such a class means without a little literature on how the grid works? Documentation, style guides, and API references are designed to help us make sense of complex systems. Sure, it doesn’t mean documentation should justify poor design and unclear naming conventions, but thinking you should be able to understand an entire project only by reading the source code is pure fantasy.</p><p>There are plenty of tools out there to help you generate documentation right from your code. I use <a href="http://warpspire.com/kss/syntax">KSS</a> for most of my projects, but CSS-Tricks shares a <a href="https://css-tricks.com/options-programmatically-documenting-css">list of alternatives</a>. Give it a try!</p><h3>“Utility classes should be used along with components”</h3><p>Yes. Absolutely. That’s precisely why it’s called utility-<em>first</em> and not utility-<em>only</em>.</p><p>Utility-first isn’t about ditching components altogether. It means you should start off with utility classes, make the most of them, and only abstract when you see repeating patterns. You’re allowing your project to grow while remaining flexible, and identifying actual components over time, when patterns start to emerge.</p><p>It is crucial to understand that a component isn’t <em>just</em> a similar-looking “block” that you <em>can</em> reuse. It’s a pattern that is strongly tied to your specific project. Sure, you’re probably going to use tons of .btn and .modal, so it makes sense to abstract them early on. But are you positive you’re going to ever reuse .testimonial? Or at least reuse it <em>enough</em> to make it worth being a new component? Will it always look like this in every context, or is it specific to the homepage? Keep your options open. It’s a lot easier to later abstract a composite style into a component than to try and undo one.</p><h3>“It makes redesigning/theming a nightmare”</h3><p>Because atomic CSS is strongly tied to your design, this can make things more difficult when you have to do a redesign or develop an alternate theme. It’s far from impossible though, and there are a few things you can do to make your utility-first CSS more suited to these kinds of needs.</p><p>You can start by keeping class names not too specific. Instead of .margin-bottom-8, you can use a more abstract name like .margin-bottom-xxs. This way you can change the value without making the names invalid.</p><p>Another approach would be to create <strong>aliases</strong>. Imagine you’re building an app that has light and dark mode: some colors would change, some others wouldn’t. We don’t want to make all our color utilities contextual: .background-primary and .background-secondary don’t tell us what color is behind the class. You don’t want an entire color system like that. Yet, you could still have color utilities with proper color names (.background-lime or .background-red), and generate aliases for those which might need to change for theming purposes.</p><pre>// CSS</pre><pre>/* Backgrounds */</pre><pre>.background-lime {<br>  background: #cdf2b0;<br>}</pre><pre>.background-off-white, .background-light {<br>  background: #ebefe8;<br>}</pre><pre>.background-dark-grey, .background-dark {<br>  background: #494a4f;<br>}</pre><pre>/* Colors */</pre><pre>.color-lime {<br>  color: #cdf2b0;<br>}</pre><pre>.color-off-white, .color-light {<br>  color: #ebefe8;<br>}</pre><pre>.color-dark-grey, .color-dark {<br>  color: #494a4f;<br>}</pre><pre>// HTML</pre><pre>&lt;div class=&quot;background-light&quot;&gt;<br>  &lt;h2 class=&quot;color-lime&quot;&gt;Ezekiel 25:17&lt;/h2&gt;<br>  &lt;p class=&quot;color-dark&quot;&gt;The path of the righteous man is beset on all sides by the inequities of the selfish and the tyranny of evil men...&lt;/p&gt;<br>&lt;/div&gt;</pre><p>From here, all you have to do is write a JavaScript function that toggles all .*-light and .*-dark classes. And for elements that don’t need to change, you can use the original color classes.</p><p>This method works well, but if you have a lot of classes to switch it may end up hurting performances. DOM manipulations are expensive. You want to reduce them as much as possible if you can. Luckily, there’s a nifty technique involving CSS variables (thanks to Adam Wathan for coming up with it) which makes everything simpler.</p><pre>// CSS</pre><pre>:root {<br>  --green: #42f49b;<br>  --off-white: #ebefe8;<br>  --dark-grey: #494a4f;<br>}</pre><pre>.theme-dark {<br>  --background: var(--dark-grey);<br>  --text: var(--off-white);<br>}</pre><pre>.theme-light {<br>  --background: var(--off-white);<br>  --text: var(--dark-grey);<br>}</pre><pre>.color-lime {<br>  color: var(--green);<br>}</pre><pre>.color-theme {<br>  color: var(--text);<br>}</pre><pre>.background-theme {<br>  background: var(--background);<br>}</pre><pre>// HTML</pre><pre>&lt;div class=&quot;theme-light&quot;&gt;<br>  &lt;div class=&quot;background-theme&quot;&gt;<br>  &lt;h2 class=&quot;color-lime&quot;&gt;Ezekiel 25:17&lt;/h2&gt;<br>  &lt;p class=&quot;color-theme&quot;&gt;The path of the righteous man is beset on all sides by the inequities of the selfish and the tyranny of evil men...&lt;/p&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>We defined colors with CSS variables and assigned different values for each context. Depending on the encompassing class, <a href="https://jsfiddle.net/hurmktbz">all colors will change thanks to ancestor inheritance</a>. If you were to allow theme switching, all you’d have to do is change .theme-light into .theme-dark on the parent &lt;div&gt;, and all colors would adapt.</p><p>This technique only works if you don’t have to support Internet Explorer and Edge below version 15. Otherwise, go for the first technique and use CSS ancestor inheritance system to avoid having to toggle too many variables. If you have to assign a text color to an entire block, <strong>set it on the parent instead of the children</strong>.</p><pre>/* Nope */<br>&lt;div class=&quot;background-light&quot;&gt;<br>  &lt;h2 class=&quot;color-lime&quot;&gt;Ezekiel 25:17&lt;/h2&gt;<br>  &lt;p class=&quot;color-dark&quot;&gt;The path of the righteous man is beset on all sides by the inequities of the selfish and the tyranny of evil men.&lt;/p&gt;<br>  &lt;p class=&quot;color-dark&quot;&gt;Blessed is he, who in the name of charity and good will, shepherds the weak through the valley of darkness, for he is truly his brother&#39;s keeper and the finder of lost children.&lt;/p&gt;<br>  &lt;p class=&quot;color-dark&quot;&gt;And I will strike down upon thee with great vengeance and furious anger those who would attempt to poison and destroy my brothers.&lt;/p&gt;<br>  &lt;p class=&quot;color-dark&quot;&gt;And you will know my name is the Lord when I lay my vengeance upon thee.&lt;/p&gt;<br>&lt;/div&gt;</pre><pre>/* Yes */<br>&lt;div class=&quot;background-light color-dark&quot;&gt;<br>  &lt;h2 class=&quot;color-lime&quot;&gt;Ezekiel 25:17&lt;/h2&gt;<br>  &lt;p&gt;The path of the righteous man is beset on all sides by the inequities of the selfish and the tyranny of evil men.&lt;/p&gt;<br>  &lt;p&gt;Blessed is he, who in the name of charity and good will, shepherds the weak through the valley of darkness, for he is truly his brother&#39;s keeper and the finder of lost children.&lt;/p&gt;<br>  &lt;p&gt;And I will strike down upon thee with great vengeance and furious anger those who would attempt to poison and destroy my brothers.&lt;/p&gt;<br>  &lt;p&gt;And you will know my name is the Lord when I lay my vengeance upon thee.&lt;/p&gt;<br>&lt;/div&gt;</pre><h3>Embracing change, within reason</h3><p>Having strong opinions is great. Not everything has to be settled by finding a middle ground. But there’s a clear line to draw between <strong>being opinionated </strong>and <strong>being reluctant to change</strong>.</p><p>We, as developers, <strong>must be the first to embrace change</strong>. Looking back at my first reaction towards utility-first CSS, I realize how important it is we keep an open mind instead of rushing to pick a side. <strong>It doesn’t matter how experienced <em>we think</em> we are</strong>. Experience is great, but it can also make us believe we already have all we need to make judgment calls and don’t need to dive deeper to understand new concepts.</p><p><strong>Software development changes every day</strong>. Our industry is still young, and we’re figuring things out as we go. It doesn’t mean we should throw away the past, and continuously refactor all our projects to keep up with the latest trends. Past knowledge is the foundation of today’s discoveries. But just because something is tried and true, doesn’t mean it’s set in stone. It’s important we approach novelty with critical thinking.</p><p>We’ll probably move on from utility-first CSS at some point, like how we got past many things we used to consider the pinnacle of front-end development. In the meantime, let’s try to stay as open-minded as possible, and <strong>do what’s best for the industry, the projects, and the users</strong>.</p><p>Want to learn more about utility-first CSS and how to use it in your projects? Go read <a href="https://css-tricks.com/growing-popularity-atomic-css/">On the Growing Popularity of Atomic CSS</a> on CSS Tricks and <a href="https://adamwathan.me/css-utility-classes-and-separation-of-concerns">CSS Utility Classes and “Separation of Concerns”</a> on Adam Wathan’s blog. You can also check out utility-first libraries on this <a href="https://css-tricks.com/need-css-utility-library/">curated list</a> by CSS Tricks.</p><p>Originally published at <a href="https://frontstuff.io/in-defense-of-utility-first-css">frontstuff.io</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f406acee6fb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/in-defense-of-utility-first-css-4f406acee6fb">In Defense of Utility-First CSS</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>