You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在create-react-app中启用CSS modules?react-scripts 1.1.4版本失效

How to Enable CSS Modules in create-react-app (react-scripts 1.1.4)

Hey there! Let's break down why the .module.css trick isn't working for you, and walk through the solutions to get CSS Modules up and running.

Why the .module.css method fails with react-scripts 1.1.4

Dan Abramov's tweet about enabling CSS Modules via .module.css files refers to a feature that was natively added in create-react-app v2.0.0 and later. Your current version, react-scripts 1.1.4, is part of the v1.x series which doesn't support this out-of-the-box—this is exactly why renaming your stylesheets isn't having any effect.


This is the simplest and most future-proof approach, as it lets you use the native CSS Modules support Dan mentioned:

  • Run the upgrade command in your project directory:
    # Using npm
    npm install react-scripts@latest --save
    # Using yarn
    yarn add react-scripts@latest
    
  • Rename your stylesheet files to follow the [filename].module.css pattern (e.g., Button.module.css instead of Button.css)
  • Import and use the styles in your React components like this:
    import styles from './Button.module.css';
    
    function Button() {
      return <button className={styles.button}>Click Me</button>;
    }
    

Solution 2: Enable CSS Modules in react-scripts 1.1.4 (Without Upgrading)

If you can't upgrade for some reason, you can use react-app-rewired to modify the CRA config without ejecting:

  1. Install the required dev dependencies:
    # Using npm
    npm install react-app-rewired react-app-rewire-css-modules --save-dev
    # Using yarn
    yarn add react-app-rewired react-app-rewire-css-modules --dev
    
  2. Create a config-overrides.js file in your project root with this content:
    const rewireCssModules = require('react-app-rewire-css-modules');
    
    module.exports = function override(config, env) {
      config = rewireCssModules(config, env);
      return config;
    };
    
  3. Update your package.json scripts to use react-app-rewired instead of the default react-scripts:
    "scripts": {
      "start": "react-app-rewired start",
      "build": "react-app-rewired build",
      "test": "react-app-rewired test --env=jsdom"
    }
    
  4. Now you can use CSS Modules with your existing .css files—no need to rename them. Import and use styles like this:
    import styles from './Button.css';
    
    function Button() {
      return <button className={styles.button}>Click Me</button>;
    }
    

内容的提问来源于stack exchange,提问作者Muhammad Saqib

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:13:32