PHPackages                             mak/css-module-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Templating &amp; Views](/categories/templating)
4. /
5. mak/css-module-bundle

ActiveSymfony-bundle[Templating &amp; Views](/categories/templating)

mak/css-module-bundle
=====================

A Symfony bundle to use css-modules with twig and webpack encore

v0.1.3(4mo ago)215MITPHPPHP &gt;=8.2CI failing

Since Jun 5Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/mkrauser/css-module-bundle)[ Packagist](https://packagist.org/packages/mak/css-module-bundle)[ Docs](https://twig.symfony.com)[ RSS](/packages/mak-css-module-bundle/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (7)Versions (5)Used By (0)

CssModuleBundle [![Tweet](https://camo.githubusercontent.com/cb820a0ecc9645168e33b03925d7f14691262ddbaeaf66a0a91697803d0cba2d/68747470733a2f2f696d672e736869656c64732e696f2f747769747465722f75726c2f687474702f736869656c64732e696f2e7376673f7374796c653d736f6369616c)](https://twitter.com/intent/tweet?text=Use%20CSS%20Modules%20with%20Symfony&url=https://github.com/mkrauser/css-module-bundle&hashtags=css-modules-bundle)
================================================================================================================================================================================================================================================================================================================================================================================================================================

[](#cssmodulebundle-)

**CssModuleBundle** is a Symfony bundle that enables the use of CSS Modules and JavaScript module imports directly within Twig templates.

### Sample:

[](#sample)

```
/* button.module.scss */
.button {
    background-color: blue;
    color: white;
    padding: 10px 20px;
    border-radius: 5px;
    text-decoration: none;
}
```

```
{# Import the CSS module defined above #}
{% importModule 'button.module.scss' %}

{# Use a scoped class from the imported module by string #}
Click me

{# ...or by array #}
Click me
```

🎯 Purpose
---------

[](#-purpose)

CSS Modules bring scoped class names to CSS, avoiding naming collisions and promoting modular architecture. This bundle brings the same benefits to Symfony + Twig.

If you're familiar with [CSS Modules](https://github.com/css-modules/css-modules), particularly in React, you'll appreciate the ability to:

- Use short, unique class names without global conflicts.
- Keep styles encapsulated at the component level.
- Apply the same development patterns in Symfony projects with Twig.

---

📦 Installation
--------------

[](#-installation)

```
composer require mak/css-module-bundle
```

---

⚙️ Configuration
----------------

[](#️-configuration)

### Webpack Encore Setup

[](#webpack-encore-setup)

In your `webpack.config.js`:

```
const glob = require("glob-all");

Encore
    // ...
    .addEntry('app', [
        './assets/app.js',
        ...glob.sync(["./templates/**/*.html.twig"]),
    ])
    .addLoader({
        test: /\.twig$/,
        use: [
            {
                loader: path.resolve(
                    __dirname,
                    "vendor/mak/css-module-bundle/Resources/webpack/TwigLoader.js"
                ),
            },
        ],
    })
    .configureCssLoader((options) => {
        options.modules = {
            auto: (resourcePath) => /\.module\.\w+$/i.test(resourcePath),
            localIdentName: "[hash:base64:5]",
        };
    })
```

### Symfony Bundle Configuration

[](#symfony-bundle-configuration)

```
# config/packages/mak_css_module.yaml
mak_css_module:
    localIdentName: '[hash:base64]'
    localIdentContext: '%kernel.project_dir%'
    localIdentHashSalt: null
```

---

🚀 Usage in Twig
---------------

[](#-usage-in-twig)

```
{# Import CSS module into the current template context #}
{% importModule 'button.module.scss' %}

{# Apply a scoped class from the imported module #}
Click me

{# Alternatively, specify the module explicitly #}
Click me
```

> > **⚠️ Note:**
> > Imported modules only apply to the current template to prevent unintended side effects in included templates.

---

🧱 Component-First Folder Structure
----------------------------------

[](#-component-first-folder-structure)

Inspired by Atomic Design and modern component-based development, you can colocate templates, styles, and JavaScript files:

```
templates/
├─ components/
│  ├─ atoms/
│  │  ├─ sample-atom/
│  │  │  ├─ sample-atom.html.twig
│  │  │  ├─ sample-atom.module.css
│  │  │  ├─ sample_atom_controller.js
│  ├─ molecules/
│  ├─ organisms/
├─ pages/
├─ base/

```

With `importModule`, CSS and JS are automatically bundled for each component.

---

⚡ Stimulus Integration
----------------------

[](#-stimulus-integration)

To enable autoloading of Stimulus controllers in your templates:

```
// assets/bootstrap.js
import { definitionsFromContext } from "@hotwired/stimulus-webpack-helpers";
...
app.load(
  definitionsFromContext(
    require.context(
      "@symfony/stimulus-bridge/lazy-controller-loader!../templates",
      true,
      /\.[jt]sx?$/
    )
  )
);
```

This allows Webpack to bundle Stimulus controllers alongside your Twig templates.

---

🔍 Internals
-----------

[](#-internals)

- The bundle mimics Webpack’s `css-loader` functionality to hash class names.
- `importModule` registers the module within a template.
- `scope()` computes the hashed class name at **compile time**.
- Included templates are isolated to prevent shared scope.

> **⚠️ Note:**
> `scope()` accepts raw string input for class names. Input validation is out of scope.

---

❓ Frequently Asked Questions
----------------------------

[](#-frequently-asked-questions)

### How to use Twig CSS Modules with PurifyCSS, UnCSS, or PurgeCSS?

[](#how-to-use-twig-css-modules-with-purifycss-uncss-or-purgecss)

These tools remove unused CSS by scanning for class names. Since CSS module hashes aren't explicitly written in Twig/JS, you must:

1. Add a prefix to all CSS module hashes:

```
mak_css_module:
  localIdentName: '_[hash:base64]'
```

2. Update your Encore config similarly.
3. Safelist the prefix in PurgeCSS:

```
new PurgeCSSPlugin({
    paths: glob.sync([
        `${PATHS.templates}/**/*.html.twig`,
        `${PATHS.assets}/**/*.{js,ts}`,
    ], { nodir: true }),
    safelist: {
        deep: [/^_/],
    },
    extractors: [
        {
            extractor: purgeHtml,
            extensions: ["html", "twig"],
        },
    ],
})
```

---

### Is there a performance impact?

[](#is-there-a-performance-impact)

No. All hashing is done at Twig **compile time**, so runtime performance is unaffected. In fact, shorter hashed class names may slightly improve render efficiency.

---

### How to use SASS, LESS, or other preprocessors?

[](#how-to-use-sass-less-or-other-preprocessors)

No additional setup is needed. Just use `.module.scss` or `.module.less` as usual. Webpack will handle them according to your preprocessor loader configuration.

---

### Can I use global variables or mixins in CSS Modules?

[](#can-i-use-global-variables-or-mixins-in-css-modules)

Yes, using [`sass-resources-loader`](https://github.com/shakacode/sass-resources-loader):

```
Encore
    .configureLoaderRule("scss", (loaderRule) => {
        loaderRule.oneOf.forEach((rule) => {
            rule.use.push({
                loader: "sass-resources-loader",
                options: {
                    resources: [
                        path.resolve(__dirname, "./node_modules/bootstrap5/scss/_mixins.scss"),
                        path.resolve(__dirname, "./assets/scss/global.scss"),
                    ],
                },
            });
        });
    });
```

This will inject shared mixins and variables into every `.module.scss` file.

---

🙌 Contributing &amp; Feedback
-----------------------------

[](#-contributing--feedback)

Pull requests are welcome! If you find bugs or have feature suggestions, feel free to open an issue or tweet about it using [\#css-modules-bundle](https://twitter.com/intent/tweet?hashtags=css-modules-bundle).

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance78

Regular maintenance activity

Popularity9

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~74 days

Total

4

Last Release

122d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/b9aefabc109b7f6310a081a25fd4152202bd76df5e01639127fe38a07be5d01f?d=identicon)[mkrauser](/maintainers/mkrauser)

---

Top Contributors

[![mkrauser](https://avatars.githubusercontent.com/u/494845?v=4)](https://github.com/mkrauser "mkrauser (15 commits)")

---

Tags

bundletwigcss-modules

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Rector

Type Coverage Yes

### Embed Badge

![Health badge](/badges/mak-css-module-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/mak-css-module-bundle/health.svg)](https://phpackages.com/packages/mak-css-module-bundle)
```

###  Alternatives

[twig/extra-bundle

A Symfony bundle for extra Twig extensions

91492.0M315](/packages/twig-extra-bundle)[symfony/ux-icons

Renders local and remote SVG icons in your Twig templates.

555.8M69](/packages/symfony-ux-icons)[yellowskies/qr-code-bundle

Symfony Barcode &amp; QR Code Generator Bundle with Twig extension

36682.9k](/packages/yellowskies-qr-code-bundle)[nucleos/antispam-bundle

This bundle provides some basic features to reduce spam in symfony forms.

52105.1k](/packages/nucleos-antispam-bundle)[jbouzekri/phumbor-bundle

A Symfony Bundle to use the minimal Thumbor PHP client from webfactory/phumbor

25740.0k1](/packages/jbouzekri-phumbor-bundle)[symfony/ux-toolkit

A tool to easily create a design system in your Symfony app with customizable, well-crafted Twig components

1432.0k](/packages/symfony-ux-toolkit)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
