@dr.pogodin/babel-plugin-react-css-modules

中文文档
8.0.0发布于 2026/10/11BSD-3-ClauseTypeScriptES Module近 30 天下载 2.9万

Transforms styleName to className using compile time CSS module resolution.

原始使用文档
文档目录17 节
  1. Contributors
  2. Content
  3. Usage Examples
  4. Installation
  5. React
  6. React Native
  7. Migration v7 ⇒ v8
  8. Configuration
  9. Plugin Options
  10. Configurate syntax loaders
  11. transform
  12. Custom Attribute
  13. Server-Side Rendering
  14. Under the hood
  15. How does it work?
  16. Project history
  17. css-loader compatibility

Babel Plugin: React CSS Modules

Latest NPM Release NPM monthly downloads CircleCI GitHub Repo stars Dr. Pogodin Studio

Babel plugin for advanced CSS modules support in React:

  • It transforms styleName attributes of JSX components into className using compile-time CSS module resolution, allowing for a cleaner use of CSS modules in React.

  • For server-side rendering (SSR) it can replace named stylesheet imports by class name mapping objects, and remove anonymous stylesheet imports.

This plugin is a fork and further evolution of the original babel-plugin-react-css-modules (the original babel-plugin-react-css-modules has been abandoned by its owner since 2019, and it does not work with the modern Webpack versions).

Sponsor

Contributors

Content

Usage Examples

Assuming style.css in the following examples is compiled as CSS Module.

Without this plugin

import S from './styles.css';

export default function Component() {
  return (
    <div className={S.container}>
      <h1 className={S.title}>Example</div>
      <p styleName={S.text}>Sample text paragraph.</p>
      <p className={`${S.text} ${S.special}`}>
        Sample text paragraph with special style.
      </p>
    </div>
  );
}

With this plugin

import './styles.css';

export default function Component() {
  return (
    <div styleName="container">
      <h1 styleName="title">Example</div>
      <p styleName="text">Sample text paragraph.</p>
      <p styleName="text special">
        Sample text paragraph with special style.
      </p>
    </div>
  );
}

With this plugin and multiple stylesheets

Assuming:

  • Styles container, title, and text are defined in styles-01.css.
  • Style special is defined in styles-02.css.
  • The plugin's autoResolveMultipleImports option is enabled (default).
import './styles-01.css';
import './styles-02.css';

export default function Component() {
  return (
    <div styleName="container">
      <h1 styleName="title">Example</div>
      <p styleName="text">Sample text paragraph.</p>
      <p styleName="text special">
        Sample text paragraph with special style.
      </p>
    </div>
  );
}

If both files, styles-01.css and styles-02.css contain styles with the same names, thus making auto resolution impossible, this plugin allows explicit stylesheet prefixes:

import S1 from './styles-01.css';
import S2 from './styles-02.css';

export default function Component() {
  return (
    <div styleName="S1.container">
      <h1 styleName="S1.title">Example</div>
      <p styleName="S1.text">Sample text paragraph.</p>
      <p styleName="S1.text S2.special">
        Sample text paragraph with special style.
      </p>
    </div>
  );
}

With this plugin and runtime resolution

import './styles-01.css';
import './styles-02.css';

export default function Component({ special }) {
  let textStyle = 'text';
  if (special) textStyle += ' special';

  return (
    <div styleName="container">
      <h1 styleName="title">Example</div>
      <p styleName={textStyle}>Sample text paragraph.</p>
      <p styleName={textStyle}>
        Sample text paragraph with special style.
      </p>
    </div>
  );
}

In the case when the exact style value is not known at the compile time, like in this example, the plugin will inject necessary code to correctly resolve the styleName at runtime (which is somewhat less performant, but otherwise works fine).

SSR scenario

Consider such component, which uses a named stylesheet import in order to use it in some other ways, beside simple styling, e.g. to also display the classname mapping:

import S from './style.css';

export default function Component() {
  return (
    <div styleName="container">
      {JSON.stringify(S)}
    </div>
  )
}

While by default this plugin transforms it into the following code (leaving it to Webpack to handle ./style.scss import for the actual CSS bundling, and to generate the correct JS output):

import S from './style.css';

export default function Component() {
  return (
    <div className="12345">
      {JSON.stringify(S)}
    </div>
  )
}

For server-side environment, if you don't compile server-side code with Webpack, you'll need to replace ./style.css with valid JS code. That is exactly what this plugin does with replaceImport option enabled, it outputs:

const S = {
  container: '12345',
  // Other stylesheet keys, if any.
};

export default function Component() {
  return (
    <div className="12345">
      {JSON.stringify(S)}
    </div>
  )
}

CommonJS require() support

The plugin works the same with require('./style.css') CSS imports.

Installation

React

  • The core CSS Modules functionality should be enabled and configured elsewhere in your React project:

    • With bare Webpack see Native CSS.
    • With other frameworks refer to their corresponding documentation.
  • Install this plugin as a direct dependency (in the edge-cases, when the compile-time styleName resolution is impossible, this plugin falls back to the runtime resolution).

    npm install --save @dr.pogodin/babel-plugin-react-css-modules
    
  • Install Webpack at least as a development dependency:

    npm install --save-dev webpack
    
  • Add this plugin to Babel configuration:

    {
      "plugins": [
        ["@dr.pogodin/react-css-modules", {
          "context": "/your/webpack/compilation/context",
          "localIdentName": "[fullhash:base64:6]",
          "uniqueName": "output.uniqueName used by Webpack",
        }]
      ]
    }
    

    BEWARE:

    • The localIdentName option value MUST match the localIdentName option of the Webpack's CSS generator. By default, Webpack uses [uniqueName]-[id]-[local] for development builds, and [fullhash] for production builds (see: https://webpack.js.org/guides/native-css/#generator-options); we recommend to explicitly set the same, matching values both in this plugin's and in the Webpack generator's configurations, including the hash digest kind & length (e.g. [fullhash:base64:6]).

    • The fullhash calculated by Webpack includes the path of CSS file, relative to the Webpack's compilation context, and the output.uniqueName value. Be sure to set context and uniqueName settings of this plugin to the appropriate values, and double-check the class names generated by Webpack, and by this plugin do match.

    • Alternatively, this plugin provides a simplified, stable implementation for getLocalIdent function (taken from a selected old version of css-loader). It only supports class name placeholders supported by the interpolateName() function of loader-utils, but it resolves CSS file paths relative to the closest package.json file, it does not factor uniqueName into the hash, and it supports an additional package placeholder, which is substituded by the name value from the closest package.json — these come handy for compilation of libraries.

      You can use this getLocalIdent function (its factory, to be precise) like this:

      Within Webpack Config

      import { localIdentNameFactory } from '@dr.pogodin/babel-plugin-react-css-modules/utils';
      
      export {
        module: {
          generator: {
            'css/module': {
              localIdentName: localIdentNameFactory('[fullhash:base64:6]'),
            },
          },
        },
      };
      

      Within Babel Config

      import { localIdentNameFactory } from '@dr.pogodin/babel-plugin-react-css-modules/utils';
      
      export {
        plugins: [
          ["@dr.pogodin/react-css-modules", {
            localIdentName: localIdentNameFactory('[fullhash:base64:6]'),
            // NOTE: No need for `context` and `uniqueName` settings here.
          }]
        ]
      };
      

React Native

If you'd like to get this working in React Native, you're going to have to allow custom import extensions, via a rn-cli.config.js file:

module.exports = {
  getAssetExts() {
    return ["scss"];
  }
}

Remember, also, that the bundler caches things like plugins and presets. If you want to change your .babelrc (to add this plugin) then you'll want to add the --reset-cache flag to the end of the package command.

Migration v7 ⇒ v8

v8 version of this plugin drops compatibility with now deprecated css-loader (the old way to process CSS with Webpack), and aims to be compatible with Native CSS processing instead. To migrate:

  • Switch to Native CSS in your Webpack configuration.

  • Upgrade this plugin to v8 version, and update its configuration:

    • Replace generateScopedName option by localIdentName.

      If you used a string value, be sure to set context and uniqueName options of this plugin to match context and output.uniqueName values used by Webpack.

      If you used getLocalIdent() & generateScopedName() functions exported by this plugin, replace them by the new localIdentNameFactory() export.

    • Be sure to double-check that class names generated by Webpack and this plugin are matching each other. In particular, Webpack includes into hashes the paths of CSS files relative to the context, and output.uniqueName values, it is easy to make a mistake and end up with Webpack and this plugin getting different values of these parameters.

Configuration

Plugin Options

These are valid plugin options. All are optional, but the overall configuration should be compatible with that of Webpack, thus defaults may not work for you.

  • context — string — Must match Webpack context. Defaults process.cwd().

  • exclude — string — A RegExp that will exclude otherwise included files e.g., to exclude all styles from node_modules: exclude: 'node_modules'.

  • filetypes — Configurate syntax loaders like sugarss, LESS and SCSS, and extra plugins for them.

  • localIdentName — function | string — Allows to customize the exact styleName to className conversion algorithm. For details see Generating scoped names. Defaults [file]__[local]__[hash:base64:6].

  • replaceImport — boolean — Replaces / removes stylesheet imports for server-side rendering purposes. See details below. Defaults false.

  • handleMissingStyleName — ignore | throw | warn — Determines what should be done for undefined CSS modules (using a styleName for which there is no CSS module defined). Defaults "throw".

  • attributeNames — Custom Attribute Mapping

  • skip — boolean — Whether to apply plugin if no matching attributeNames found in the file. Defaults false.

  • transform — function — If provided, each CSS source loaded by the plugin will be passed through this function, alongside its path, and this plugin's options, and the output of this function will be used in place of the original CSS.

  • autoResolveMultipleImports — boolean — Allows multiple anonymous imports ifstyleName is only in one of them. Defaults true.

Configurate syntax loaders

To add support for different CSS syntaxes (e.g. SCSS), perform the following two steps:

  1. Add the postcss syntax loader as a development dependency:

    npm install postcss-scss --save-dev
    
  2. Add a filetypes syntax mapping to the Babel plugin configuration. For example for SCSS:

    "filetypes": {
      ".scss": {
        "syntax": "postcss-scss"
      }
    }
    

    And optionally specify extra plugins:

    "filetypes": {
      ".scss": {
        "syntax": "postcss-scss",
        "plugins": [
          "postcss-nested"
        ]
      }
    }
    

    NOTE: postcss-nested is added as an extra plugin for demonstration purposes only. It's not needed with postcss-scss because SCSS already supports nesting.

    Postcss plugins can have options specified by wrapping the name and an options object in an array inside your config:

      "plugins": [
        ["postcss-import-sync2", {
          "path": ["src/styles", "shared/styles"]
        }],
        "postcss-nested"
      ]
    

transform

function transform(cssSource, cssSourceFilePath, pluginOptions): string

The transform function, if provided as the transform option of this plugin, will be called for each loaded CSS source with three arguments:

  • cssSource — string — The loaded CSS code.
  • cssSourceFilePath — string — The path of loaded CSS file.
  • pluginOptions — object — The options set for this plugin.

It should return a string, the actual CSS code to use.

Custom Attribute

You can set your own attribute mapping rules using the attributeNames option.

It's an object, where keys are source attribute names and values are destination attribute names.

For example, the <NavLink> component from React Router has an activeClassName attribute to accept an additional class name. You can set "attributeNames": { "activeStyleName": "activeClassName" } to transform it.

The default styleName ⇒ className transformation will not be affected by an attributeNames value without a styleName key. Of course you can use { "styleName": "somethingOther" } to change it, or use { "styleName": null } to disable it.

Server-Side Rendering

If replaceImport flag is set, this plugin will remove or replace original stylesheet imports, which is needed for server-side rendering:

// Anonymous imports are removed from the code:
import 'path/to/style.css';

// Default and named imports are replaced in the following manner:

// Before:
import styles, {
  className,
  otherClassName as alias,
} from 'path/to/style.css';

// After:
const styles = {
  className: 'generatedClassName',
  otherClassName: 'otherGeneratedClassName',
},
className = 'generatedClassName',
alias = 'otherGeneratedClassName';

// Also this kind of import:
import * as style from 'path/to/style.css';

// is replaced by:
const style = {
  className: 'generatedClassName',
  otherClassName: 'otherGeneratedClassName',
};

Under the hood

How does it work?

This plugin does the following:

  1. Builds the index of all stylesheet imports per file (imports of files with .css, and other configured CSS extensions).

  2. Uses postcss to parse the matching CSS files into a lookup of CSS module references.

  3. Iterates through all JSX element declarations.

  4. Parses the styleName (and/or other configured) attribute values into anonymous and named CSS module references.

  5. Finds the CSS class name matching the CSS module reference:

    • If styleName value is a string literal, generates a string literal value.
    • If styleName value is a jSXExpressionContainer, uses a helper function (getClassName) to construct the className value at the runtime.
  6. Removes the styleName attribute from the element.

  7. Appends the resulting className to the existing className value (creates className attribute if one does not exist).

  8. With the replaceImport feature enabled, it also removes anonymous style imports from the code, and replaces named imports by the corresponding constant declarations.

Project history

This plugin is a fork and further evolution of the original babel-plugin-react-css-modules.

  • The original plugin has been abandoned by its owner since 2019, and does not work with modern Webpack versions since 2020.

  • This fork, created in 2020, receives regular maintenance, works with the latest Webpack versions, and gets new features as necessary.

There is no reference to this fork in the original plugin's repository because the owner of the original plugin removed announcements of this fork from his repository, and banned this fork's author from further commenting in there — he had no time to care about his stale plugin, but he has found a moment to spoil chances of users to find a working alternative.

css-loader compatibility

The original plugin, and the versions of this fork prior to its v8 aimed for compatibility with now deprecated css-loader (the legacy way to process CSS by Webpack, replaced by Native CSS). If you still need to work with css-loader in your project, consult the css-loader compatibility table of for plugin versions.

版本与发布记录

@dr.pogodin/babel-plugin-react-css-modules 共发布 66 个版本,首次发布于 2020/08/09;过去 12 个月发布了 18 个版本。

版本发布日期距今
8.0.0latest2026/10/111 个月前
8.0.0-alpha.8v8-alpha2026/10/091 个月前
8.0.0-alpha.72026/10/061 个月前
8.0.0-alpha.52026/09/271 个月前
8.0.0-alpha.42026/09/271 个月前
8.0.0-alpha.32026/09/261 个月前

关于 @dr.pogodin/babel-plugin-react-css-modules 的常见问题

@dr.pogodin/babel-plugin-react-css-modules 是什么?

Transforms styleName to className using compile time CSS module resolution.

如何安装 @dr.pogodin/babel-plugin-react-css-modules?

在项目目录运行 npm install @dr.pogodin/babel-plugin-react-css-modules,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:postcss(8)、webpack(>=5.108)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@dr.pogodin/babel-plugin-react-css-modules 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@dr.pogodin/babel-plugin-react-css-modules 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@dr.pogodin/babel-plugin-react-css-modules 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@dr.pogodin/babel-plugin-react-css-modules 可以商用吗?

@dr.pogodin/babel-plugin-react-css-modules 使用 BSD-3-Clause 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。另外不得用原作者名义为衍生产品背书。以上为概括,不构成法律意见,请以许可原文为准。

@dr.pogodin/babel-plugin-react-css-modules 的下载量有多少?

根据 npm 官方下载统计,@dr.pogodin/babel-plugin-react-css-modules 在 2026/10/13 – 2026/11/11 这 30 天内被下载 29,012 次,日均约 967 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@dr.pogodin/babel-plugin-react-css-modules 还在维护吗?

最新版本 8.0.0 发布于 2026/10/11(1 个月前);至今共发布 66 个版本,其中过去 12 个月发布了 18 个;首次发布于 2020/08/09。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。