CSS Modules

CSS Modules

CSS Modules allows you to scope your styles to a single component by obfuscating the class name, this talk will look at using CSS Modules with React, Angular, TypeScript, Bootstrap and how to use localised class names in tests.

De17bad13d4e0a786c92e66553f00e88?s=128

Paul Heasley

February 21, 2018
Tweet

Transcript

  1. CSS Modules Paul Heasley
 @pheasley

  2. CSS: So Simple .bgred { background-color: red; }

  3. becomes .text-left { text-align: left; } .styles__text-left__1GS2g { text-align: left;

    }
  4. Stylesheet .row { background-color: pink; } .first-row { background-color: green;

    } webpack / css-loader JavaScript import { row: 'styles__row__1GS2g', firstRow: 'styles__text-left__3JSLq', 'first-row': 'styles__text-left__3JSLq' }
  5. Import styles in JavaScript import styles from './styles.css'; document.querySelector('#some-element').classList.add(styles.textLeft);

  6. Global styles :global(.btn) { background-color: blue; }

  7. Opt-in local styles :local(.my-local-style) { background-color: blue; }

  8. LESS / SASS :global(.global-parent) { .local-child: { color: pink; }

    } becomes .global-parent .styles__local-child__3JSLq { color: pink; }
  9. import React from 'react'; import PropTypes from 'prop-types'; import styles

    from './styles.module.css'; const HelloWorld = ({ name }) => ( <div className={styles.welcome}>Hello, {name || 'world'}</div> ); HelloWorld.propTypes = { name: PropTypes.string }; export default HelloWorld; React
  10. Angular var angular = require('angular'); var styles = require('./styles.css'); var

    Controller = function() { this.styles = styles; }; angular .module('pageup.hello-world', []) .component('pupHelloWorld', { template: '<div class="{{$ctrl.styles.welcome}}">Hello, {{$ctrl.name || "world"}}</div>', bindings: { name: '<' }, controller: Controller });
  11. TypeScript import styles from './styles.css'; results in TS2307: Cannot find

    module ‘./styles.css'.
  12. TypeScript const styles = require('./styles.css'); npm install typings-for-css-modules-loader or

  13. Tests with CSS Modules this.element.find('.welcome')

  14. Tests with CSS Modules this.element.find('[data-test-target=welcome]') const styles = require(‘components/hello-world/styles.css'); describe('Hello

    World component', function () { it('should greet the world given no name supplied', function () { var greeting = _element.find('.' + styles.welcome) expect(greeting.text()).to.equal('Hello, world'); }); }); or
  15. Bootstrap 1. Treat as global styles <div class="row"> <div class="col-xs-10

    {{$ctrl.styles.ruleHeading}}"> <span>Rule</span> </div> <div class="col-xs-2 {{$ctrl.styles.criteriaClearAll}}"> <span>Clear</span> </div> </div>
  16. Bootstrap 2. Shared CSS module const styles = require('components/hello-world/styles.css'); const

    globalStyles = require('styles/global.css'); <a ng-class="[globalStyles.btn, styles.btn]" href="#"> Home </a>
  17. Thanks.