We will use Vite's built-in support for CSS modules.
Note
If you get lost, you can check how embroider-css-modules-vite-app
is set up.
You will need these dependencies to build an Embroider app with Vite.
@embroider/compat
@embroider/core
@embroider/vite
vite
For PostCSS, here is what you likely need at minimum.
autoprefixer
Finally, some packages to improve your developer experience (DX).
All in all, here's a one-line command for installation:
pnpm install --dev \
@embroider/compat @embroider/core @embroider/vite vite \
autoprefixer \
embroider-css-modules type-css-modules
1. Needed only if you have a TypeScript project.
In this step, you will update one file: vite.config.mjs
.
Vite supports CSS modules out of the box, so we just need to pass the option css.modules
.
vite.config.mjs
import {
compatPrebuild,
hbs,
optimizeDeps,
resolver,
scripts,
templateTag,
} from '@embroider/vite';
import { babel } from '@rollup/plugin-babel';
import { resolve } from 'path';
import { defineConfig } from 'vite';
const root = 'node_modules/.embroider/rewritten-app';
export default defineConfig({
+ css: {
+ modules: {
+ generateScopedName: '[sha512:hash:base64:5]',
+ },
+ },
root,
esbuild: false,
cacheDir: resolve('node_modules', '.vite'),
plugins: [
hbs(),
templateTag(),
scripts(),
resolver(),
compatPrebuild(),
babel({
babelHelpers: 'runtime',
extensions: ['.gjs', '.js', '.hbs', '.ts', '.gts'],
}),
],
optimizeDeps: optimizeDeps(),
server: {
port: 4200,
watch: {
ignored: [`!**/${root}/**`],
},
},
build: {
outDir: resolve(process.cwd(), 'dist'),
rollupOptions: {
input: {
main: resolve(root, 'index.html'),
tests: resolve(root, 'tests/index.html'),
},
},
},
});
Note
You have a few options for generateScopedName
. See Set up CSS modules (v2 addons) - Configure hashing.
Vite supports PostCSS. To set up PostCSS plugins like autoprefixer
, see Set up CSS modules (apps built with Webpack) - Set up PostCSS.
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.ts
Note, we write the file extension .module.css
explicitly.
import Component from '@glimmer/component';
import styles from './hello.module.css';
export default class HelloComponent extends Component {
styles = styles;
}
app/components/hello.hbs
Note
type-css-modules
will create declaration files with the extension *.module.css.d.ts
. The configuration remains the same.
Again, the only difference from an app built with Webpack is the file extension *.module.css
.