# Ember + Modern CSS

**URL:** <https://discuss.emberjs.com/t/ember-modern-css/19614>\
**Category:** Design\
**Created:** [July 13, 2022, 7:11pm UTC](https://discuss.emberjs.com/t/ember-modern-css/19614 "2022-07-13T19:11:58Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![evoactivity](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.emberjs.com/evoactivity/32/15988_2.png) [@evoactivity](https://discuss.emberjs.com/u/evoactivity)\
**Post date:** [July 13, 2022, 7:11pm UTC](https://discuss.emberjs.com/t/ember-modern-css/19614/1 "2022-07-13T19:11:59Z")

</div>

Forget everything you know about CSS + Ember. If you use any of the following `ember-postcss`, `ember-css-modules`, `ember-component-css` then this guide is for you.

Together we are going to take an embroider enabled Ember app and configure a webpack pipeline for our application’s CSS using PostCSS and tailwind.

This guide will not go over enabling embroider in your application, I will be using a fresh ember app with full embroider compatibility (route splitting included).

An example app is available at [GitHub - evoactivity/ember-modern-css: Forget everything you know about CSS + Ember. If you use any of the following ember-postcss, ember-css-modules, ember-component-css then this guide is for you.](https://github.com/evoactivity/ember-modern-css) (including this article with syntax highlighting)

## Goal

An ember app using tailwind with livereload and full tailwind JIT compatibility. This will be achieved with webpack’s `postcss-loader` addon, opening up the rest of the postcss ecosystem.

## Benefits

Using webpack to bundle our CSS opens up our Ember app to the rest of the CSS ecosystem. We no longer need to reach for the addons mentioned above or write our own addons for dealing with the ember-cli CSS pipeline. We just ignore the legacy CSS pipeline and by doing so we get some easy wins.

1. Route split, lazy loading CSS
2. CSS Modules out of the box
3. If a webpack addon exists you can use it (more on this in future articles)

## Dependencies

We are aiming to use tailwind and PostCSS so we must install them both along with some other dependencies.

```bash
npm add postcss postcss-loader tailwindcss autoprefixer cssnano --save-dev

```

Create our config files in the project root

```js
// ./postcss.config.js

const env = process.env.EMBER_ENV || 'development';

const plugins = [
  require('tailwindcss/nesting'),
  require('tailwindcss')({ config: './tailwind.config.js' }),
  require('autoprefixer'),
];

if (env === 'production') {
  plugins.push(
    require('cssnano')({
      preset: 'default',
    })
  );
}

module.exports = {
  plugins,
};

```

```js
// ./tailwind.config.js

const path = require('node:path');
const defaultTheme = require('tailwindcss/defaultTheme');
const appEntry = path.join(__dirname, 'app');
const relevantFilesGlob = '**/*.{html,js,ts,hbs,gjs,gts}';

module.exports = {
  content: [path.join(appEntry, relevantFilesGlob)],
  theme: {
    extend: {
      fontFamily: {
        sans: ['Inter var', ...defaultTheme.fontFamily.sans],
      },
    },
  },
  plugins: [],
};

```

We need to tell eslint these are node files, open `.eslintrc.js`

```js
// .eslintrc.js
  // ...
  overrides: [
  // node files
  {
    files: [
      './.eslintrc.js',
      './.prettierrc.js',
      './.template-lintrc.js',
      './ember-cli-build.js',
      './testem.js',
      './blueprints/*/index.js',
      './config/**/*.js',
      './lib/*/index.js',
      './server/**/*.js',
      // add new config files
      './postcss.config.js',
      './tailwind.config.js',
    ],
  // ...

```

## Webpack Configuration

Assuming you already have embroider installed and fully compatible we need to update the webpack config. Open `ember-cli-build.js`

Near the bottom you should have your embroider config

```js
return require('@embroider/compat').compatBuild(app, Webpack, {
  staticAddonTestSupportTrees: true,
  staticAddonTrees: true,
  staticHelpers: true,
  staticModifiers: true,
  staticComponents: true,
  splitAtRoutes: ['route1', 'route2'],
  packagerOptions: {
    webpackConfig: {},
  },
  extraPublicTrees: [],
});

```

Let’s add our new config, I have added comments to each line

```js
function isProduction() {
  return EmberApp.env() === 'production';
}

return require('@embroider/compat').compatBuild(app, Webpack, {
  staticAddonTestSupportTrees: true,
  staticAddonTrees: true,
  staticHelpers: true,
  staticModifiers: true,
  staticComponents: true,
  splitAtRoutes: ['route1', 'route2'],
  packagerOptions: {
    // publicAssetURL is used similarly to Ember CLI's asset fingerprint prepend option.
    publicAssetURL: '/',
    // Embroider lets us send our own options to the style-loader
    cssLoaderOptions: {
      // don't create source maps in production
      sourceMap: isProduction() === false,
      // enable CSS modules
      modules: {
        // global mode, can be either global or local
        // we set to global mode to avoid hashing tailwind classes
        mode: 'global',
        // class naming template
        localIdentName: isProduction()
          ? '[sha512:hash:base64:5]'
          : '[path][name]__[local]',
      },
    },
    webpackConfig: {
      module: {
        rules: [
          {
            // When webpack sees an import for a CSS files
            test: /\.css$/i,
            exclude: /node_modules/,
            use: [
              {
                // use the PostCSS loader addon
                loader: 'postcss-loader',
                options: {
                  sourceMap: isProduction() === false,
                  postcssOptions: {
                    config: './postcss.config.js',
                  },
                },
              },
            ],
          },
        ],
      },
    },
  },
  extraPublicTrees: [],
});

```

## Let’s talk directory structure

### Legacy `./styles` and `./styles/app.css`

`ember-cli` expects `styles/app.css` to exist, but we do not want any css inside of this file. Just an empty app.css is required.

We cannot delete this directory or file and we cannot import from this directory so for all intents and purposes this directory does not exist.

Hopefully we can delete it one day.

### New `./assets` directory

Since we have limitations on our `./styles` directory this will be where our entrypoint CSS is going to be created.

```bash
mkdir -p app/assets && touch app/assets/styles.css

```

Let’s add our tailwind styles

```css
/* ./app/assets/styles.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

```

## Importing CSS

We now need to import our CSS into our application. We are going to import our CSS into our `./app.js`. The reason for this is to ensure load order when we build for production. Webpack injects `<link>` tags in the order they are imported and we want our entrypoint to always be first.

```js
import Application from '@ember/application';
import Resolver from 'ember-resolver';
import loadInitializers from 'ember-load-initializers';
import config from 'ember-modern-css/config/environment';
// import our applications style entrypoint
import './assets/styles.css';

export default class App extends Application {
  modulePrefix = config.modulePrefix;
  podModulePrefix = config.podModulePrefix;
  Resolver = Resolver;
}

loadInitializers(App, config.modulePrefix);

```

At this point your should have tailwind installed and your CSS will rebuild on changes to your templates and js files.

## CSS Modules

Now that we can import our CSS files we can make use CSS modules with our components.

Say we have

```auto
./app/components/my-widget/
  - index.js
  - index.hbs

```

We can co-locate our styles along side our components.

```auto
./app/components/my-widget/
  - index.js
  - index.hbs
  - styles.css

```

```css
/* We mark the classes we want hashed with :local() */
:local(.root) {
  background: red;
}

:local(.anotherHashedClass) {
  background: green;
}

.normalClass {
  background: blue;
}

```

Open your component’s index.js

```js
import Component from '@glimmer/component';
// import our styles, this time named
import styles from './styles.css';

export default class MyWidget extends Component {
  // we need our styles to be accessible from our template
  // so add a property in your class.
  styles = styles;
}

```

When built our `.root` class will become something like `.h4e` so we need to lookup the correct class string. `styles` is created as a property of the component, giving us access to `{{this.styles.myClassName}}` in our template.

```hbs
<h1 class={{this.styles.root}}>Widget</h1>

```

This can become tedious when using longer or multiple classes, or mixing hashed classes with non-hashed classes

Wouldn’t it be nice if instead of this

```hbs
<h1
  class={{concat
    this.styles.root
    ' '
    this.styles.anotherHashedClass
    ' bg-red-100 mb-10'
  }}
>Widget</h1>

```

We could write

```hbs
<h1
  class='{{styles this "root anotherHashedClass"}} bg-red-100 mb-10'
>Widget</h1>

```

So let’s create a helper

```bash
ember g helper styles

```

```js
import Helper from '@ember/component/helper';

export default class Styles extends Helper {
  compute(params) {
    const [context, classNames] = params;

    if (typeof context?.styles === 'undefined') {
      console.error(
        'Import and assign your styles to your component class or controller class'
      );
      return '';
    }

    const classString = classNames
      .split(' ')
      .map((name) => {
        if (context?.styles && context?.styles[name]) {
          return context.styles[name];
        }

        console.error(`The class or id named '${name}' does not exist`);

        return '';
      })
      .join(' ');

    return classString;
  }
}

```

We can now update our template

```hbs
<h1 class={{styles this 'root'}}>Widget</h1>

```

## Typescript

If you are using typescript in your project it will complain about not being able to import .css files. To remedy this we need to tell typescript what to expect when importing a css file.

Open your `global.d.ts` and add

```typescript
declare module '*.css' {
  const styles: { [className: string]: string };
  export default styles;
}

```

## Next Steps

You can now customize your PostCSS and Tailwind configs, add your own PostCSS addons and make it work for you and your team.

Once you have your CSS modernized I would suggest managing your images and fonts in a similar way. That will be my next article, using webpack’s `asset/loader` for fonts and `responsive-loader` to generate responsive images from a single image import.

---

<div class="post-metadata">

**Author:** ![NullVoxPopuli](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.emberjs.com/nullvoxpopuli/32/18691_2.png) [@NullVoxPopuli](https://discuss.emberjs.com/u/NullVoxPopuli)\
**Post date:** [August 13, 2022, 4:54pm UTC](https://discuss.emberjs.com/t/ember-modern-css/19614/2 "2022-08-13T16:54:09Z")

</div>

This is fantastic!

Next up (and a curiosity for me) – how much can we optimize this? According to: [https://twitter.com/frontstuff\_io/status/1558489518474420224](https://twitter.com/frontstuff_io/status/1558489518474420224) we can then pass things through css-loader to minify class names – idk how that’d work since all the JS/TS/etc needs processed as well. But “the dream” could/would be a post-processing step on everything similar to what [css-blocks](https://css-blocks.com/) is doing. (or at least determining if it’s worth it for performance-sensitive apps)

---

<div class="post-metadata">

**Author:** ![steveszc](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.emberjs.com/steveszc/32/10051_2.png) [@steveszc](https://discuss.emberjs.com/u/steveszc)\
**Post date:** [August 23, 2022, 2:25pm UTC](https://discuss.emberjs.com/t/ember-modern-css/19614/3 "2022-08-23T14:25:10Z")

</div>

For anyone else that comes across this, if you want to get images working with this webpack config you can add the following rule to the rules array in the webpackConfig in ember-cli-build.js

```auto
{
  test: /\.(png|svg|jpg|jpeg|gif|webp)$/i,
  type: 'asset/resource',
},

```

---

<div class="post-metadata">

**Author:** ![evoactivity](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.emberjs.com/evoactivity/32/15988_2.png) [@evoactivity](https://discuss.emberjs.com/u/evoactivity)\
**Post date:** [July 13, 2023, 12:26am UTC](https://discuss.emberjs.com/t/ember-modern-css/19614/4 "2023-07-13T00:26:37Z")

</div>

For anyone who followed my ember modern css guide, with the embroider version 3.1.0 and up you will need to update your css exclude in the ember-cli-build file to

```js
exclude: /node_modules((?!\/rewritten-app).)*$/

```

To make sure the postcss pipeline runs.

> <https://github.com/embroider-build/embroider/issues/1515>
>
> pre version 3.1 if you wanted to set additional webpack module rules (for exampl…e setting up postcss-loader)
> it would not be uncommon (for performance reasons) to exclude all matches against \`/node\_modules/\`
> eg:
> \`\`\`js {
> packagerOptions: {
> cssLoaderOptions: {
> sourceMap: isProduction() === false,
> },
> webpackConfig: {
> module: {
> rules: \[{
> test: /\\.css$/i,
> exclude: /node\_modules/,
> use: \[{
> loader: 'postcss-loader',
> options: {
> sourceMap: isProduction() === false,
> postcssOptions: {
> config: './postcss.config.js',
> },
> },
> },\],
> },\],
> },
> },
> }
> }
> \`\`\`
> since 3.1 this has the sideeffect of excluding your app files as well as they now live within rewritten-app
> 
> writing this to have a discussion on what people think is the appropriate action to take going forward
> I'm suggesting we start a gotchas doc where we talk about this
> 
> in the above example to avoid processing every .css file under node\_modules I would recommend extending the \`test\` condition to target the \`rewritten-app\` folder as well

> **[GitHub - evoactivity/ember-modern-css: Forget everything you know about CSS +...](https://github.com/evoactivity/ember-modern-css#webpack-configuration)**
>
> Forget everything you know about CSS + Ember. If you use any of the following ember-postcss, ember-css-modules, ember-component-css then this guide is for you. - GitHub - evoactivity/ember-modern-c...

---

<div class="post-metadata">

**Author:** ![evoactivity](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.emberjs.com/evoactivity/32/15988_2.png) [@evoactivity](https://discuss.emberjs.com/u/evoactivity)\
**Post date:** [July 14, 2023, 11:38pm UTC](https://discuss.emberjs.com/t/ember-modern-css/19614/5 "2023-07-14T23:38:16Z")

</div>

A more performant version would be

```diff
+ test: /(node_modules\/\.embroider\/rewritten-app\/)(.*\.css)$/i,
- exclude: /node_modules/,

```

---

<div class="post-metadata">

**Author:** ![leepfrog](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.emberjs.com/leepfrog/32/18129_2.png) [@leepfrog](https://discuss.emberjs.com/u/leepfrog)\
**Post date:** [July 28, 2023, 11:12pm UTC](https://discuss.emberjs.com/t/ember-modern-css/19614/6 "2023-07-28T23:12:19Z")

</div>

One slight adjustment to the steps above.

I found that I was getting a `Cannot find module 'foo.css' or its corresponding type declarations.` error from Glint, though the CSS modules were working correctly.

Thanks to some pairing with @ecoactivity, we found that the issue was with putting the css type declarations into the `global.d.ts` file. If you put the type declaration into `glint-registry.d.ts` (or separate declarations file) instead, the error will clear. (Would love to know why this is the case… 😃 )

---

<div class="post-metadata">

**Author:** ![ijlee2](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.emberjs.com/ijlee2/32/16190_2.png) [@ijlee2](https://discuss.emberjs.com/u/ijlee2)\
**Post date:** [July 31, 2023, 3:47pm UTC](https://discuss.emberjs.com/t/ember-modern-css/19614/7 "2023-07-31T15:47:10Z")

</div>

Yes, TypeScript will need to understand what it means to import a `*.css` file and the “shape” of what’s exported from the file. You can use [`type-css-modules`](https://github.com/ijlee2/embroider-css-modules/blob/main/packages/type-css-modules/README.md) to auto-create the `*.css.d.ts` files.

---

<div class="post-metadata">

**Author:** ![evoactivity](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.emberjs.com/evoactivity/32/15988_2.png) [@evoactivity](https://discuss.emberjs.com/u/evoactivity)\
**Post date:** [August 9, 2023, 1:41pm UTC](https://discuss.emberjs.com/t/ember-modern-css/19614/8 "2023-08-09T13:41:01Z")

</div>

If you’re using windows you will need to account for backslashes

```auto
test: /(node_modules(\/|\\)\.embroider(\/|\\)rewritten-app(\/|\\))(.*\.css)$/i,

```

---

<div class="post-metadata">

**Author:** ![tcjr](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.emberjs.com/tcjr/32/14655_2.png) [@tcjr](https://discuss.emberjs.com/u/tcjr)\
**Post date:** [January 16, 2024, 5:09pm UTC](https://discuss.emberjs.com/t/ember-modern-css/19614/9 "2024-01-16T17:09:25Z")

</div>

I’ve been using this for several months, and it works wonderfully.

`ember-apply` now also has [a tool](https://github.com/NullVoxPopuli/ember-apply?tab=readme-ov-file#tailwind-webpack) that can do all these steps for you. In an Ember application with embroider:

```auto
npx ember-apply tailwind-webpack

```

---

<div class="post-metadata">

**Author:** ![NullVoxPopuli](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.emberjs.com/nullvoxpopuli/32/18691_2.png) [@NullVoxPopuli](https://discuss.emberjs.com/u/NullVoxPopuli)\
**Post date:** [January 16, 2024, 6:47pm UTC](https://discuss.emberjs.com/t/ember-modern-css/19614/10 "2024-01-16T18:47:24Z")

</div>

> [@tcjr](#):
>
> I’ve been using this for several months, and it works wonderfully.

Additionally, there is a [non-webpack integrated approach](https://github.com/NullVoxPopuli/ember-apply/#tailwind) (automated Tailwind’s docs for the tailwind-cli, and adds an `<link>` tag to your `index.html`)

```bash
npx ember-apply tailwind

```

it works 100% of the time in

- non-embroider
- webpack
- vite

🎉

no need to change anything about your CSS pipeline when switching build environments

---

<div class="post-metadata">

**Author:** ![colenso.x-b-e](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.emberjs.com/colenso.x-b-e/32/18299_2.png) [@colenso.x-b-e](https://discuss.emberjs.com/u/colenso.x-b-e)\
**Post date:** [February 21, 2024, 2:28pm UTC](https://discuss.emberjs.com/t/ember-modern-css/19614/11 "2024-02-21T14:28:48Z")

</div>

Our app uses a `app.scss` file i.e. sass. What additional things would I need to do get it working this new way?
