Frontend Development 7 min read

Automatic CSS Modules Detection in React Projects Using a Babel Plugin and Webpack Configuration

This article explains how to automatically enable CSS Modules in React applications by creating a Babel plugin that adds a query parameter to CSS imports and configuring webpack loaders to recognize the parameter, providing a concise and practical solution for scoped styling.

360 Tech Engineering
360 Tech Engineering
360 Tech Engineering
Automatic CSS Modules Detection in React Projects Using a Babel Plugin and Webpack Configuration

When using CSS in a React project, importing a CSS file directly (e.g., import './index.css' ) makes its styles global, so developers often rely on CSS Modules to scope class names uniquely.

Umi 3 can automatically recognize when a CSS import should be treated as a CSS Module; this article explores the underlying implementation using a custom Babel plugin.

The Babel plugin traverses the AST, looks for ImportDeclaration nodes, checks that the specifiers array is non‑empty and that the imported file has a CSS‑related extension, then appends the query string ?css_modules to the import source.

Example plugin code:

const { extname } = require('path');
const CSS_FILE_EXTENSIONS = ['.css', '.scss', '.sass', '.less'];
module.exports = () => ({
  visitor: {
    ImportDeclaration(path) {
      const { specifiers, source } = path.node;
      const { value } = source;
      if (specifiers.length > 0 && CSS_FILE_EXTENSIONS.includes(extname(value))) {
        source.value = `${value}?css_modules`;
      }
    }
  }
});

In the webpack configuration, resourceQuery is used to match the ?css_modules suffix, enabling the modules option of css-loader for those files while leaving other CSS files untouched.

module.exports = {
  module: {
    rules: {
      oneOf: [
        {
          test: /\.css$/,
          resourceQuery: /css_modules/,
          loader: 'css-loader',
          options: { modules: true }
        },
        {
          test: /\.css$/,
          loader: 'css-loader'
        }
      ]
    }
  }
};

The same pattern applies to Less, Sass, and other preprocessors by adding the appropriate loaders. The plugin is published as @umijs/babel-plugin-auto-css-modules and can be enabled via the flag option to customize the query string.

reactWebpackUmiCSS ModulesBabel Plugin
360 Tech Engineering
Written by

360 Tech Engineering

Official tech channel of 360, building the most professional technology aggregation platform for the brand.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.