/ #ember-addon

Using PostCSS through ember-css-modules

Using PostCSS through ember-css-modules

ember-css-modules

ember-css-modules is a great Ember addon which makes it possible to put CSS files next to the component and its template file. This is especially great with Ember Octane's new co-location feature (be sure to use ember-css-modules 1.3.0-beta.1 or higher!).

components
 - my-component.js
 - my-component.hbs
 - my-component.css

The addon provides a local-class attribute which you can use instead of HTML's own class attribute. Styles defined using the local-class attribute are fully scoped to the component.

// my-component.hbs
<div local-class="my-class" ...attributes></div>

// my-component.css
.my-class {
  background: orange;
}

PostCSS

PostCSS is a CSS postprocessing pipeline. The pipeline can be configured with many available plugins. postcss-preset-env is a plugin which allows you to use upcoming CSS features now. Kind of like what Babel does for JavaScript. This makes features like CSS nesting usable while also including autoprefixer which makes your CSS compatible with older browsers.

.this-css {
  &.is-nested {
    background: orange;
  }
}

<div class="this-css is-nested"></div>

How to use them together

What you might not know is that ember-css-modules is actually built on top of PostCSS. This means we don't need the separate ember-cli-postcss addon to use PostCSS!

ember install ember-css-modules
yarn add --dev postcss-preset-env

ember-css-modules provides a setting to pass PostCSS plugins. In order to configure postcss-preset-env you need to add it to ember-css-modules' plugins section in your app's ember-cli-build.js. We also require Ember's own /config/targets.js configuration and pass it to the plugin's configuration so that it will follow the same browser targets as the rest of the Ember app.

'use strict';

const EmberApp = require('ember-cli/lib/broccoli/ember-app');
const { browsers } = require('./config/targets');

module.exports = function(defaults) {
  let app = new EmberApp(defaults, {
    // Add options here

    cssModules: {
      plugins: [
        require('postcss-preset-env')({
          browsers,
          features: {
            'nesting-rules': true
          }
        })
      ]
    }
  });

  return app.toTree();
};

And that's it!

For further configuration be sure to look at the ember-css-modules documentation for configuring PostCSS or take a look at the plugin section for available plugins.