Progressive Migration Strategy from Legacy CSS to CSS Modules in a Monolithic Codebase

Comprehensive guide to progressively migrate legacy CSS to CSS Modules in React with Webpack, ensuring compatibility and minimal UI regression.

Brief Introduction

Progressive Migration Strategy from Legacy CSS to CSS Modules in a Monolithic Codebase (css)
DESCRIPTION:
Complete and robust example of how to progressively migrate a monolithic codebase from legacy CSS to CSS Modules, maintaining compatibility and minimizing regression risks. Includes Webpack configurations, React component examples with CSS Modules, and management of coexisting legacy CSS.

ADDITIONAL NOTES:
The strategy involves keeping legacy CSS for existing components and gradually introducing CSS Modules for new or refactored components. The Webpack configuration is dual to handle both CSS types without conflicts. Legacy class names remain global, while CSS Modules ensure isolation and collision prevention.

EXPLANATIONS:
- The Webpack configuration uses two distinct rules for CSS files: one for *.module.css files (CSS Modules) and one for *.css files (legacy CSS).
- Legacy React components import global CSS and use fixed string classNames, while modular components import styles as objects and use dynamic classNames.
- Progressive migration allows refactoring one component at a time, testing and releasing without breaking the UI.
- Using CSS Modules avoids global contamination and facilitates long-term maintenance.
- The package.json contains scripts to start the dev server and build production, easing integration into the existing workflow.

Example Code: css

/*
  Example Webpack configuration to support legacy CSS and CSS Modules
  and two React components: one legacy and one modular.
*/

// webpack.config.js
const path = require('path');

module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  module: {
    rules: [
      {
        test: /\.module\.css$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              modules: {
                localIdentName: '[name]__[local]___[hash:base64:5]',
              },
            },
          },
        ],
      },
      {
        test: /(?<!\.module)\.css$/,
        use: [
          'style-loader',
          'css-loader',
        ],
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env', '@babel/preset-react'],
          },
        },
      },
    ],
  },
  devServer: {
    static: './dist',
    hot: true,
  },
};

/*
  Legacy CSS: styles/legacy-button.css
  Defines global classes without isolation.
*/

/* styles/legacy-button.css */
.legacy-button {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s ease;
}

.legacy-button:hover {
  background-color: #0056b3;
}

/*
  CSS Module: styles/Button.module.css
  Isolates classes with hashed naming.
*/

/* styles/Button.module.css */
.button {
  background-color: #28a745;
  color: white;
  border: none;
  padding: 12px 24px;
  font-size: 18px;
  cursor: pointer;
  border-radius: 6px;
  transition: background-color 0.3s ease;
}

.button:hover {
  background-color: #1e7e34;
}

/*
  Legacy React component using legacy CSS
*/

// src/components/ButtonLegacy.js
import React from 'react';
import '../styles/legacy-button.css'; // global import

/**
 * Legacy button with global CSS classes
 */
export function ButtonLegacy({ onClick, children }) {
  return (
    <button className="legacy-button" onClick={onClick}>
      {children}
    </button>
  );
}

/*
  Modular React component using CSS Modules
*/

// src/components/ButtonModular.js
import React from 'react';
import styles from '../styles/Button.module.css'; // CSS Module import

/**
 * Modular button with isolated CSS classes
 */
export function ButtonModular({ onClick, children }) {
  return (
    <button className={styles.button} onClick={onClick}>
      {children}
    </button>
  );
}

/*
  React entry point
*/

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { ButtonLegacy } from './components/ButtonLegacy';
import { ButtonModular } from './components/ButtonModular';

function App() {
  return (
    <div style={{ padding: '20px' }}>
      <h1>Legacy CSS to CSS Modules Migration Demo</h1>
      <h2>Legacy Component</h2>
      <ButtonLegacy onClick={() => alert('Legacy button clicked!')}>Legacy</ButtonLegacy>
      <h2>Modular Component</h2>
      <ButtonModular onClick={() => alert('Modular button clicked!')}>Modular</ButtonModular>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('root'));

/*
  package.json snippet for dependencies and scripts
*/

/*
{
  "name": "css-migration-example",
  "version": "1.0.0",
  "scripts": {
    "start": "webpack serve --open",
    "build": "webpack --mode production"
  },
  "dependencies": {
    "react": "^18.0.0",
    "react-dom": "^18.0.0"
  },
  "devDependencies": {
    "@babel/core": "^7.0.0",
    "@babel/preset-env": "^7.0.0",
    "@babel/preset-react": "^7.0.0",
    "babel-loader": "^8.0.0",
    "css-loader": "^6.0.0",
    "style-loader": "^3.0.0",
    "webpack": "^5.0.0",
    "webpack-cli": "^4.0.0",
    "webpack-dev-server": "^4.0.0"
  }
}
*/
×
×
×
Do you want to regenerate the answer?
×
Export chat
Choose export format
Generazione PDF in corso…
Allegati
×
You are about to close the chat and switch to the image generator. If you are not logged in, you will lose our chat. Do you confirm?
You are viewing a shared chat in temporary mode. It will not be saved.
×
Saved prompts
×
Private note
×
Label
×
Search all chats
×
Your insights
Analyzing…
×
AI Preferences
Assistant name 30
Answer length
AI model
Structured answers
Include examples
Use emojis
Guide me, don't solve Hints and questions instead of a ready answer
More settings →
×
Share this chat
Anyone opening this link can view the chat or add it to their profile as their own chat.
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
Shared chat
Someone shared a chat with you. Do you want to just view it or add it to your chats?
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
×

Saved messages

Loading...

×

Chat History

example-programs · CHAT HISTORY

Loading...

AI Preferences

×
  • BasicQuick and essential answers for study
  • MediumHigher quality for study and programming
  • AdvancedComplex reasoning and detailed analysis
Explain Steps

What do you need?

React Components: ButtonLegacy, ButtonModular

Legacy CSS: styles/legacy-button.css

CSS Modules: styles/Button.module.css

Webpack Configuration: support for both legacy CSS and CSS Modules

Software Dependencies: react, react-dom, css-loader, style-loader, babel-loader, webpack, webpack-cli

Babel Configuration: JSX and ES6+ support

Arduino Wiring/Pinout: not applicable (frontend software)

Configurations: package.json scripts for build and dev server

Similar Topics

Using text-decoration to underline or remove underline from links
Learn how to use CSS text-decoration to remove or add underline on links with a simple hover effect for better usability and clear link styling.
Change the alignment of an image with basic CSS properties
Learn how to change the horizontal alignment of an image inside a container using basic CSS properties like text-align and margin for beginners.
Product Card Grid with CSS Grid and Responsive Alignment
Responsive product card grid using CSS Grid and Flexbox for clean, adaptable layouts from mobile to desktop with easy customization.
Creating a Magazine-Style Layout Using CSS Grid Template Areas
Responsive magazine-style layout using CSS Grid template areas for easy customization with header, navigation, main, sidebar, and footer sections.
Dropdown Menu Only with CSS and Pseudo-classes
Complete CSS-only dropdown menu using :hover and :focus-within for accessible, responsive, and customizable navigation without JavaScript.
Responsive Three-Column Layout with CSS Grid
Responsive three-column layout using CSS Grid and media queries for seamless adaptation from desktop to mobile devices with clean, readable design.
Scalable Typography System with CSS Variables (font-size, line-height)
Complete scalable typography system using CSS variables for consistent font-size and line-height, optimized for responsive design and easy maintenance.
Dark mode and light mode with CSS custom properties and a toggle class
Complete guide to implement dark and light mode using CSS custom properties and toggle class for dynamic theme switching in any web project.