Skip to content

Latest commit

 

History

History
120 lines (79 loc) · 3.3 KB

set-up-css-modules-apps-built-with-vite.md

File metadata and controls

120 lines (79 loc) · 3.3 KB

Set up CSS modules (apps built with Vite)

Apps built with Vite are called "v2 apps." The blueprint for v2 apps are still in development, so this page will stay away from any blueprint details (e.g. Embroider dependencies).

Good news is, Vite provides CSS modules out of the box. We just need to configure our app a bit.

  1. Install dependencies
  2. Configure Vite
  3. Style your first component
  4. Style your first route

Note

If you get lost, you can check how my-v2-app is set up.

Install dependencies

You can install these packages to improve your developer experience (DX).

Here's a one-line command for installation:

pnpm install --dev embroider-css-modules type-css-modules

1. Needed only if you have a TypeScript project.

Configure Vite

In this step, you will update one file: vite.config.mjs. Pass the option css.modules.

vite.config.mjs
import { classicEmberSupport, ember, extensions } from '@embroider/vite';
import { babel } from '@rollup/plugin-babel';
import { defineConfig } from 'vite';

export default defineConfig({
+   css: {
+     modules: {
+       generateScopedName: 'your-ember-app__[sha512:hash:base64:5]',
+     },
+   },
  plugins: [
    classicEmberSupport(),
    ember(),
    babel({
      babelHelpers: 'runtime',
      extensions,
    }),
  ],
});

Note

You have a few options for generateScopedName. See Set up CSS modules (v2 addons) - Configure hashing.

Set up PostCSS

Vite supports PostCSS. To set up PostCSS plugins like autoprefixer, see Set up CSS modules (apps built with Webpack) - Set up PostCSS.

Style your first component

We can use embroider-css-modules in the same way as we would in an app built with Webpack, with one exception:

Important

Vite requires CSS module files to have the file extension *.module.css.

Hence, when we create the component <Hello>, we name the stylesheet hello.module.css instead:

app/components/hello.module.css
.container {
  color: magenta;
  font-family: monospace;
  font-size: 1.5rem;
  font-weight: 500;
  padding: 1rem;
}
app/components/hello.gts

Note, we write the file extension .module.css explicitly.

import styles from './hello.module.css';

<template>
  <div class={{styles.container}}>
    Hello world!
  </div>
</template>

Style your first route

Again, the only difference from an app built with Webpack is the file extension *.module.css.