Skip to content

Instantly share code, notes, and snippets.

@tthew
Last active March 28, 2016 13:01
Show Gist options
  • Save tthew/d1f0308b883ade40f76f to your computer and use it in GitHub Desktop.
Save tthew/d1f0308b883ade40f76f to your computer and use it in GitHub Desktop.
An example of leveraging Webpack, cssmodules (via webpack + postcss) and Angular

A very basic / high-level example of how to use locally scoped cssmodules in Angular, via Webpack using the css-loader.

Read the cssmodules readme and the css-loader README for lots more high-level information. Also checkout the lower-level ICSS (interoperable css) spec/readme for the nitty gritty.

Tl;dr this approach solves many of the same problems BEM sets out to solve

This would require a refactor of existing codebases to use Webpack. But beyond that (which may or may not be trivial depending on many different factors) it appears to be a maintainable and scalable strategy.

Check out this gulp-webpack-angular-seed I put together some time ago as well as the this resume application and this mnutrition branch for examples of how to angular with webpack.

File system structure:

  |- my-component/
     |-- my-component.directive.js
     |-- my-component.tpl.html
     |-- my-component.css

CSS

// scope is local by default
.myComponent { 

}

// Define a class in the global namespace;
:global(.global-class-name) { 
  color: blue; 
}

ES5 implementation

'use strict'

var styles = require('./my-directive.css')
var template = require('./my-directive.tpl.html')

angular.module('example.my-directive', [])
.directive(function () {
  return {
    restrict: 'E',
    template,
    link: (scope, element) {
      // assign styles to scope property
      scope.vm = {
        styles: styles
      }
      
      // or add the className programatically
      element.addClass(styles.myComponent)
    }
  }
})

HTML

<div class="{{::vm.styles.myComponent}}">
  <!-- my-component -->
</div>

Transpiled CSS

._23_aKvs-b8bW2Vg3fwHozO {
  background: red;
}

.global-class-name {
  color: blue;
}

Rendered HTML

<div class="_23_aKvs-b8bW2Vg3fwHozO">
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment