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:
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; }
Usage in JavaScript components:
import styles from './styles.css'; element.innerHTML = `<div class="${styles.base}">CSS Modules真有趣!</div>`;
Webpack may generate after compilation:
<div class="_20WEds96_Ee1ra54-24ePy">CSS Modules真有趣!</div>
._20WEds96_Ee1ra54-24ePy { color: deeppink; max-width: 42em; margin: 0 auto; }
Class name generation is configurable, but the key is that they are dynamically generated, unique, and map to the correct style.
Frequently asked questions:
:global()
keywords to improve reusability. composes
:global(.clearfix::after) { content: ''; clear: both; display: table; } .base { composes: appearance from '../AnotherModule/styles.css'; }
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 } } ] }
: 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' }) ] };
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" } }
Summary:
CSS Modules provide a sustainable, modular, well-scoped and reusable CSS writing method, especially for large projects.
FAQ:
.module.css
extension. :global()
. composes
keyword. 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!