定制 mak/css-module-bundle 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

mak/css-module-bundle

Composer 安装命令:

composer require mak/css-module-bundle

包简介

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

README 文档

README

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

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 #}
<a class="{{ scope('button') }}">Click me</a>

{# ...or by array #}
<a class="{{ scope(['button', 'button2']) }}">Click me</a>

🎯 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, 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

composer require mak/css-module-bundle

⚙️ Configuration

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

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

🚀 Usage in Twig

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

{# Apply a scoped class from the imported module #}
<a class="{{ scope('button') }}">Click me</a>

{# Alternatively, specify the module explicitly #}
<a class="{{ scope('button', 'button.module.scss') }}">Click me</a>

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

🧱 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

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

  • 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

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]'
  1. Update your Encore config similarly.

  2. 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?

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?

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?

Yes, using 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 & 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.

mak/css-module-bundle 适用场景与选型建议

mak/css-module-bundle 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 15 次下载、GitHub Stars 达 2, 最近一次更新时间为 2025 年 06 月 05 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「twig」 「bundle」 「css-modules」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 mak/css-module-bundle 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 mak/css-module-bundle 我们能提供哪些服务?
定制开发 / 二次开发

基于 mak/css-module-bundle 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 15
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 2
  • 点击次数: 27
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 2
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-06-05