Home >Web Front-end >CSS Tutorial >Understanding the CSS Modules Methodology

Understanding the CSS Modules Methodology

Joseph Gordon-Levitt
Joseph Gordon-LevittOriginal
2025-02-23 09:57:12790browse

Understanding the CSS Modules Methodology

CSS Modules: A powerful tool for componentized CSS

This article will introduce CSS Modules, an effective way to resolve CSS global namespace conflicts and simplify component naming. It requires a certain configuration and construction process, usually used as a plug-in for Webpack or Browserify, and does not run independently.

Core advantages:

  • Local scope: CSS Modules limits CSS scope to components by default to avoid global naming conflicts.
  • Dynamic naming: The construction process will generate a unique dynamic class name, map it to the corresponding style, reduce naming conflicts, and improve modularity.
  • Scalability: Supports defining global classes and extending styles from other modules to improve code reusability and maintainability.

Working principle:

CSS Modules are implemented by importing CSS files in JavaScript modules such as React components. It creates an object that maps the class names defined in the CSS file to dynamically generated, uniquely scoped class names. These class names are used as strings in JavaScript.

For example, a simple CSS file:

<code class="language-css">.base {
  color: deeppink;
  max-width: 42em;
  margin: 0 auto;
}</code>

Usage in JavaScript components:

<code class="language-javascript">import styles from './styles.css';

element.innerHTML = `<div class="${styles.base}">CSS Modules真有趣!</div>`;</code>

Webpack may generate after compilation:

<code class="language-html"><div class="_20WEds96_Ee1ra54-24ePy">CSS Modules真有趣!</div></code>
<code class="language-css">._20WEds96_Ee1ra54-24ePy {
  color: deeppink;
  max-width: 42em;
  margin: 0 auto;
}</code>

Class name generation is configurable, but the key is that they are dynamically generated, unique, and map to the correct style.

Frequently asked questions:

  • Class name is ugly: Class name is not for the sake of aesthetics, but for the application of styles, so this is not a problem.
  • Difficulty in debugging: You can use source map for debugging. Because the style scope is clear, debugging is relatively easy.
  • Poor style reusability: CSS Modules are designed to avoid global style conflicts, but they can still expand styles by defining global classes or :global() keywords to improve reusability. composes
<code class="language-css">:global(.clearfix::after) {
  content: '';
  clear: both;
  display: table;
}

.base {
  composes: appearance from '../AnotherModule/styles.css';
}</code>
  • Depend on build tools: This is similar to Sass or PostCSS, where the build steps are necessary.

Beginner:

Building tools such as Webpack or Browserify are required.

Webpack configuration:

Add to

: webpack.config.js

<code class="language-javascript">{
  test: /\.css$/,
  use: [
    'style-loader',
    { loader: 'css-loader', options: { modules: true } }
  ]
}</code>
To generate a separate CSS file, you can use

: MiniCssExtractPlugin

<code class="language-javascript">const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
  // ... other configurations
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          { loader: 'css-loader', options: { modules: true } }
        ]
      }
    ]
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].css'
    })
  ]
};</code>

Browserify configuration (example):

Add npm script in

: package.json

<code class="language-json">{
  "scripts": {
    "build": "browserify -p [ css-modulesify -o dist/main.css ] -o dist/index.js src/index.js"
  }
}</code>

Summary:

CSS Modules provide a sustainable, modular, well-scoped and reusable CSS writing method, especially for large projects.

FAQ:

  • Advantages: Avoid class name conflicts, improve component reusability and maintainability, and support style combinations.
  • Implementation: Configure Webpack or Browserify, use the .module.css extension.
  • Global Style: Use :global().
  • Style combination: Use the composes keyword.
  • Compatible with React Compatibility: .
  • Differences from traditional CSS: Different scopes are different, traditional CSS globally, CSS Modules locally.
  • Compatible with Sass/Less: , requiring additional configuration.
  • Debug: Use source map.
  • Limitations: Build tools are required, additional configuration may be required to support media queries, etc.
  • Server-side rendering: Additional configuration is required.

The above is the detailed content of Understanding the CSS Modules Methodology. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn