Skip to content

About

Transforms styleName to className using compile time CSS module resolution.

Topics

Resources

Stars

33 stars

Watchers

2 watching

Forks

 
 

Latest commit

 

History

310 Commits

Folders and files

Repository files navigation

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

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.

About

Transforms styleName to className using compile time CSS module resolution.

Topics

Resources

Stars

33 stars

Watchers

2 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages