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

Understanding the CSS Modules Methodology

Joseph Gordon-Levitt
Release: 2025-02-23 09:57:12
Original
786 people have browsed it

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:

.base {
  color: deeppink;
  max-width: 42em;
  margin: 0 auto;
}
Copy after login

Usage in JavaScript components:

import styles from './styles.css';

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

Webpack may generate after compilation:

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

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
:global(.clearfix::after) {
  content: '';
  clear: both;
  display: table;
}

.base {
  composes: appearance from '../AnotherModule/styles.css';
}
Copy after login
  • 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

{
  test: /\.css$/,
  use: [
    'style-loader',
    { loader: 'css-loader', options: { modules: true } }
  ]
}
Copy after login
To generate a separate CSS file, you can use

: MiniCssExtractPlugin

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'
    })
  ]
};
Copy after login

Browserify configuration (example):

Add npm script in

: package.json

{
  "scripts": {
    "build": "browserify -p [ css-modulesify -o dist/main.css ] -o dist/index.js src/index.js"
  }
}
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template