The user wants a "modular CSS architecture" with specific requirements:
- CSS Modules: Scoped CSS to avoid global namespace pollution.
- PostCSS Piping: Using PostCSS for processing (likely autoprefixing, minification, maybe CSS variables or nesting).
- Per-Feature Splitting: Organizing code by feature, not just global files.
- Critical Rendering Path Goals: Optimizing for the initial load (Critical CSS).
This sounds like a request for a structural guide or a blueprint for setting up a frontend project's styling system. It's not asking for specific proprietary code or sensitive information. It's a standard software architecture question.
I need to design a system that incorporates these four elements. I will structure the response by defining the directory structure, the tooling configuration (PostCSS), the component usage (CSS Modules), and the build optimization strategy (Critical CSS).
Step 1: Directory Structure (Per-feature splitting)
I'll propose a folder structure where styles live close to the components/features they belong to.
src/features/Auth/LoginForm.module.css
src/shared/components/Button/Button.module.css
src/global/styles/ (for variables, reset)
Step 2: Tooling (PostCSS)
I need to show a postcss.config.js or similar setup.
Plugins needed:
postcss-import or postcss-easy-import (for imports).
postcss-preset-env (modern syntax).
cssnano (minification).
postcss-modules (if doing vanilla HTML/JS) or integrated into a bundler (Webpack/Vite). Since the prompt implies a custom or specific architecture, I'll assume a bundler context or a standalone script. Bundler integration (Webpack/Vite) is the standard way to handle CSS Modules. I will describe the configuration conceptually.
Step 3: CSS Modules Implementation
Explain how to use the classes.
.button { ... } -> import styles from ... -> className={styles.button}.
Step 4: Critical Rendering Path (CRP)
This is the tricky part in a modular architecture. CRP usually involves extracting CSS required for above-the-fold content.
- Strategy 1: Inlining critical CSS.
- Strategy 2: Asynchronous loading of non-critical CSS.
- Tools:
critters, critical, or purgecss (though purgecss is for unused CSS, critical is for specific path).
I'll explain how to identify the "critical" entry points versus the feature-specific chunks.
Drafting the Architecture Plan:
- Core Philosophy: Co-location and Scoping.
- File Structure: Feature-based folders.
- Build Process: The "Pipe".
- Input: CSS Modules.
- Processing: PostCSS plugins (Nesting, Variables -> Custom Properties, AutoPrefixer).
- Output: hashed css files + JSON mappings.
- CRP Strategy:
- Global styles (fonts, reset) -> Preload/Inline.
- Layout styles -> Main bundle.
- Feature styles -> Lazy loaded with the JS chunk.
Refining the "Critical" aspect:
To achieve CRP goals in a modular setup, you don't just have one CSS file. You need:
critical.css (Variables, Reset, Typography, Above-the-fold layout).
main.css (Core app shell).
[chunk].css (Specific features loaded on demand).
Safety Check:
Does this request violate any policies? No.
Does it ask for my system instructions? No.
Does it ask for a full Chain of Thought output? No, just a design.
Therefore, I will provide a comprehensive architectural guide covering directory structure, configuration, and optimization strategy.
A robust modular CSS architecture balancing developer experience (DX) with performance (Critical Rendering Path) requires a shift from "page-based" thinking to "component-based" thinking, integrated tightly with your build system.
Here is a design specification for Modular CSS Architecture using CSS Modules, PostCSS, and Critical CSS extraction.
1. Architectural Philosophy: The "Component Shell"
Instead of a single global stylesheet, we treat CSS as a dependency of the component (HTML/JS) that renders it.
- Scope: Styles are scoped locally by default using CSS Modules (hashing class names).
- Colocation: CSS files live next to their component logic (e.g.,
Button.tsx and Button.module.css).
- Piping: PostCSS acts as the compiler, transforming modern syntax and optimizing the output.
2. Directory Structure
We split styles into three distinct buckets: Global/Generic, Design Tokens, and Feature/Component.
src/
├── styles/
│ ├── tokens/ # 1. Design Tokens (Variables)
│ │ ├── colors.css
│ │ ├── typography.css
│ │ └── spacing.css
│ ├── generic/ # 2. Global Resets & Base Styles
│ │ ├── _reset.css # Normalize/Reset
│ │ ├── _typography.css # Font-face definitions
│ │ └── global.css # Imports all generic styles
│ └── critical.css # 3. The Critical Entry Point (Manual aggregation)
│
├── features/ # 4. Per-Feature Splitting
│ └── Auth/
│ ├── LoginForm.tsx
│ └── LoginForm.module.css # Scoped to LoginForm only
│
└── App.tsx # Root entry
3. The PostCSS Pipeline (.postcssrc)
We use PostCSS to enable logic inside the CSS files. This configuration handles syntax sugar, variable injection, and class name hashing.
Required Plugins:
postcss-import: Allows @import usage (resolves paths).
postcss-simple-vars (or postcss-custom-properties): Use CSS variables.
postcss-nested: Unwrap nested rules.
postcss-preset-env: Polyfills modern CSS.
cssnano: Minification (Production only).
Configuration Example:
// postcss.config.js
module.exports = {
plugins: [
require('postcss-import'), // Handle @imports
require('postcss-nested'), // Allow nesting
require('postcss-custom-properties'), // CSS Variables
require('autoprefixer'), // Vendor prefixes
process.env.NODE_ENV === 'production' ? require('cssnano') : null
].filter(Boolean)
};
4. Implementation Details
A. Defining Tokens (Variables)
Instead of relying on global pollution, we import tokens explicitly where needed, or inject them globally via postcss-import.
src/styles/tokens/colors.css
:root {
--color-primary: #3498db;
--color-bg: #ffffff;
}
B. The Critical Entry Point
To satisfy Critical Rendering Path goals, we create a specific CSS file that is inlined in the <head> of the HTML. This file should ONLY contain variables, resets, and "Above the Fold" layout (e.g., Header, Hero).
src/styles/critical.css
@import "./tokens/colors.css";
@import "./tokens/typography.css";
@import "./generic/_reset.css";
/* Critical layout skeleton */
.app-shell {
display: grid;
min-height: 100vh;
}
C. Feature Module (Scoped)
Feature styles are imported dynamically by the component. This ensures that if the LoginForm is lazy-loaded, its CSS is also lazy-loaded.
src/features/Auth/LoginForm.module.css
.container {
display: flex;
flex-direction: column;
gap: var(--spacing-md); /* Using token from colors.css if imported or global */
}
.input {
border: 1px solid var(--color-primary);
padding: 1rem;
}
5. The Build & Rendering Strategy
This is where the architecture meets the Critical Rendering Path goal.
Development Mode
- Global Styles: Imported in
App.tsx (or root file).
- Module Styles: Injected via Style Loader (HMR supported).
Production Mode (The Critical Path)
We use a two-step extraction process.
-
Inlining Critical CSS:
During the build, a tool (like critters for Webpack or critical CLI) analyzes the entry HTML/SSR output. It identifies the CSS required to render the top of the page.
- It extracts styles from
critical.css and inline JS component styles used in the initial view.
- It injects this into a
<style> tag in the <head>.
-
Async Loading (The Split):
The remaining CSS (specifically the feature modules not visible yet) is extracted into separate .css files.
- These files are loaded with
preload or loaded on-demand when the user navigates to that feature.
Webpack/Vite Concept Config:
// webpack.config.js (Conceptual)
module.exports = {
module: {
rules: [
{
test: /\.module\.css$/,
use: [
'style-loader', // In dev
// In prod: MiniCssExtractPlugin.loader (splits files)
{
loader: 'css-loader',
options: {
modules: {
localIdentName: '[name]__[local]--[hash:base64:5]'
},
importLoaders: 1
}
},
'postcss-loader' // The Pipe defined above
]
}
]
},
plugins: [
// Extracts CSS into separate files per chunk
new MiniCssExtractPlugin({
filename: '[name].[contenthash].css',
chunkFilename: '[id].[contenthash].css'
})
]
};
Summary of Performance Impact
| Technique | Rendering Impact | Why? |
|---|
| CSS Modules | High | Removes dead code via scoping; prevents specificity wars which lead to bloated CSS. |
| PostCSS Pipe | Medium | Minifies and optimizes (cssnano) ensuring the smallest possible byte size. |
| Per-Feature Split | High | Reduces the initial CSS payload. The browser doesn't parse CSS for the "Dashboard" if the user is on the "Login" page. |
| Critical Inlining | Critical | Eliminates "Flash of Unstyled Content" (FOUC) and prevents render-blocking network requests for initial paint. |
Recommended Toolchain Stack
- Bundler: Webpack 5+ or Vite.
- Processor: PostCSS 8.
- Optimization:
critters (for Webpack) or critical (standalone) for inlining critical paths.
- Minification:
cssnano.