Upgrade to Pro — share decks privately, control downloads, hide ads and more …

CSS Modules

Paul Heasley
February 21, 2018

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.

Paul Heasley

February 21, 2018
Tweet

More Decks by Paul Heasley

Other Decks in Programming

Transcript

  1. 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' }
  2. LESS / SASS :global(.global-parent) { .local-child: { color: pink; }

    } becomes .global-parent .styles__local-child__3JSLq { color: pink; }
  3. 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
  4. 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 });
  5. 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
  6. 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>
  7. 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>